27 C# Interview Questions and Answers to Know in 2019

Alex 👨🏼‍💻FullStack.Cafe - Nov 14 '18 - - Dev Community

27 C# Interview Questions and Answers to Know in 2019
Today, C# is the 4th most popular programming language, with approximately 31% of all developers using it regularly. It is also the 3rd largest community on StackOverflow (which was built using C#) with more than 1.1 million topics.

🔴 Originally published on FullStack.Cafe - Kill Your Tech & Coding Interview

Q1: What is an Object?

Topic: C#
Difficulty: ⭐

According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically".

Objects helps us to access the member of a class or struct either they can be fields, methods or properties, by using the dot.

🔗 Source: c-sharpcorner.com

Q2: What is Managed or Unmanaged Code?

Topic: C#
Difficulty: ⭐⭐

  • Managed Code - The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any language that is written in .NET Framework is managed code.
  • Unmanaged Code - The code, which is developed outside .NET framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code.

🔗 Source: c-sharpcorner.com

Q3: What is Boxing and Unboxing?

Topic: C#
Difficulty: ⭐⭐

Boxing and Unboxing both are used for type conversion but have some difference:

  • Boxing - Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.

  • Unboxing - Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.

The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.

🔗 Source: c-sharpcorner.com

Q4: What are generics in C#?

Topic: C#
Difficulty: ⭐⭐

Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

🔗 Source: c-sharpcorner.com

Q5: Why can't you specify the accessibility modifier for methods inside the interface?

Topic: C#
Difficulty: ⭐⭐

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.

🔗 Source: guru99.com

Q6: What are reference types in C#?

Topic: C#
Difficulty: ⭐⭐

The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.

In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.

🔗 Source: tutorialspoint.com

Q7: What is the difference between Interface and Abstract Class?

Topic: C#
Difficulty: ⭐⭐⭐

There are some differences between Abstract Class and Interface which are listed below:

  • A class can implement any number of interfaces but a subclass can at most use only one abstract class.
  • An abstract class can have non-abstract methods (concrete methods) while in case of interface all the methods has to be abstract.
  • An abstract class can declare or use any variables while an interface is not allowed to do so.
  • In an abstract class all data member or functions are private by default while in interface all are public, we can't change them manually.
  • In an abstract class we need to use abstract keyword to declare abstract methods while in an interface we don't need to use that.
  • An abstract class can't be used for multiple inheritance while interface can be used as multiple inheritance.
  • An abstract class use constructor while in an interface we don't have any type of constructor.

🔗 Source: c-sharpcorner.com

Q8: What is the difference between overloading and overriding?

Topic: C#
Difficulty: ⭐⭐⭐

  • Overloading is when you have multiple methods in the same scope, with the same name but different signatures.
//Overloading
public class test
{
    public void getStuff(int id)
    {}
    public void getStuff(string name)
    {}
}
Enter fullscreen mode Exit fullscreen mode
  • Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
        public virtual void getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override void getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: stackoverflow.com

Q9: What is the difference between Virtual method and Abstract method?

Topic: C#
Difficulty: ⭐⭐⭐

  • A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.
  • An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

🔗 Source: softwaretestinghelp.com

Q10: What is the difference between dynamic type variables and object type variables?

Topic: C#
Difficulty: ⭐⭐⭐

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.

🔗 Source: tutorialspoint.com

Q11: What is the output of the program below? Explain your answer.

Topic: C#
Difficulty: ⭐⭐⭐

Consider:

delegate void Printer();

static void Main()
{
        List<Printer> printers = new List<Printer>();
        int i=0;
        for(; i < 10; i++)
        {
            printers.Add(delegate { Console.WriteLine(i); });
        }

        foreach (var printer in printers)
        {
            printer();
        }
}
Enter fullscreen mode Exit fullscreen mode

This program will output the number 10 ten times.

Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.

🔗 Source: toptal.com

Q12: What is Expression Trees and how they used in LINQ?

Topic: LINQ
Difficulty: ⭐⭐⭐

An Expression Tree is a data structure that contains Expressions, which is basically code. So it is a tree structure that represents a calculation you may make in code. These pieces of code can then be executed by "running" the expression tree over a set of data.

In LINQ, expression trees are used to represent structured queries that target sources of data that implement IQueryable<T>. For example, the LINQ provider implements the IQueryable<T> interface for querying relational data stores. The C# compiler compiles queries that target such data sources into code that builds an expression tree at runtime. The query provider can then traverse the expression tree data structure and translate it into a query language appropriate for the data source.

🔗 Source: docs.microsoft.com

Q13: What is marshalling and why do we need it?

Topic: C#
Difficulty: ⭐⭐⭐⭐

Because different languages and environments have different calling conventions, different layout conventions, different sizes of primitives (cf. char in C# and char in C), different object creation/destruction conventions, and different design guidelines. You need a way to get the stuff out of managed land an into somewhere where unmanaged land can see and understand it and vice versa. That's what marshalling is for.

🔗 Source: stackoverflow.com

Q14: What are the different ways a method can be overloaded?

Topic: C#
Difficulty: ⭐⭐⭐⭐

Methods can be overloaded using different data types for parameter, different order of parameters, and different number of parameters.

🔗 Source: guru99.com

Q15: Can we have only “try” block without “catch” block in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐

Yes we can have only try block without catch block but we have to have finally block.

🔗 Source: a4academics.com

Q16: What are the uses of delegates in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐

Below are the list of uses of delegates in C#:

  • Callback Mechanism
  • Asynchronous Processing
  • Abstract and Encapsulate method
  • Multicasting

🔗 Source: a4academics.com

Q17: Can Multiple Inheritance implemented in C# ?

Topic: C#
Difficulty: ⭐⭐⭐⭐

In C#, derived classes can inherit from one base class only. If you want to inherit from multiple base classes, use interface.

🔗 Source: stackoverflow.com

Q18: What is the "yield" keyword used for in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐

Consider:

IEnumerable<object> FilteredList()
{
    foreach( object item in FullList )
    {
        if( IsItemInPartialList( item )
            yield return item;
    }
}
Enter fullscreen mode Exit fullscreen mode

Could you explain what does the yield keyword do there?


The function returns an object that implements the IEnumerable interface. If a calling function starts foreach-ing over this object the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0.

Yield has two great uses:

  • It helps to provide custom iteration without creating temp collections.
  • It helps to do stateful iteration.

The advantage of using yield is that if the function consuming your data simply needs the first item of the collection, the rest of the items won't be created.

🔗 Source: stackoverflow.com

Q19: Name some advantages of LINQ over Stored Procedures

Topic: LINQ
Difficulty: ⭐⭐⭐⭐

Some advantages of LINQ over sprocs:

  1. Type safety: I think we all understand this.
  2. Abstraction: This is especially true with LINQ-to-Entities. This abstraction also allows the framework to add additional improvements that you can easily take advantage of. PLINQ is an example of adding multi-threading support to LINQ. Code changes are minimal to add this support. It would be MUCH harder to do this data access code that simply calls sprocs.
  3. Debugging support: I can use any .NET debugger to debug the queries. With sprocs, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn't enough).
  4. Vendor agnostic: LINQ works with lots of databases and the number of supported databases will only increase. Sprocs are not always portable between databases, either because of varying syntax or feature support (if the database supports sprocs at all).
  5. Deployment: It's easier to deploy a single assembly than to deploy a set of sprocs. This also ties in with #4.
  6. Easier: You don't have to learn T-SQL to do data access, nor do you have to learn the data access API (e.g. ADO.NET) necessary for calling the sprocs. This is related to #3 and #4.

🔗 Source: stackoverflow.com

Q20: What is deep or shallow copy concept in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

  • Shallow Copy is about copying an object's value type fields into the target object and the object's reference types are copied as references into the target object but not the referenced object itself. It copies the types bit by bit. The result is that both instances are cloned and the original will refer to the same object.
  • Deep Copy is used to make a complete deep copy of the internal reference types, for this we need to configure the object returned by MemberwiseClone().

In other words a deep copy occurs when an object is copied along with the objects to which it refers.

🔗 Source: social.msdn.microsoft.com

Q21: What is multicast delegate in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

Delegate can invoke only one method reference has been encapsulated into the delegate. It is possible for certain delegate to hold and invoke multiple methods. Such delegate called multicast delegate. Multicast delegate also know as combinable delegate, must satisfy the following conditions:

  • The return type of the delegate must be void. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords.
  • Multicast delegate instance is created by combining two delegates, the invocation list is formed by concatenating the invocation list of two operand of the addition operation. Delegates are invoked in the order they are added.

Actually all delegates in C# are MulticastDelegates, even if they only have a single method as target. (Even anonymous functions and lambdas are MulticastDelegates even though they by definition have only single target.)

Consider:

ublic partial class MainPage : PhoneApplicationPage
{
    public delegate void MyDelegate(int a, int b);
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Multicast delegate
        MyDelegate myDel = new MyDelegate(AddNumbers);
        myDel += new MyDelegate(MultiplyNumbers);
        myDel(10, 20);
    }

    public void AddNumbers(int x, int y)
    {
        int sum = x + y;
        MessageBox.Show(sum.ToString());
    }

    public void MultiplyNumbers(int x, int y)
    {
        int mul = x * y;
        MessageBox.Show(mul.ToString());
    }

}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: stackoverflow.com

Q22: List some different ways for equality check in .Net

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

  • The ReferenceEquals() method - checks if two reference type variables(classes, not structs) are referred to the same memory adress.
  • The virtual Equals() method. (System.Object) - checks if two objects are equivalent.
  • The static Equals() method - is used to handle problems when there is a null value in the check.
  • The Equals method from IEquatable interface.
  • The comparison operator == - usually means the same as ReferenceEquals, it checks if two variables point to the same memory adress. The gotcha is that this operator can be overrided to perform other types of checks. In strings, for instance, it checks if two different instances are equivalent.

🔗 Source: stackoverflow.com

Q23: What is the difference between lambdas and delegates?

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

They are actually two very different things.

  • Delegate is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name.
  • Lambdas are very much like other methods, except for a couple subtle differences:
    • A normal method is defined in a "statement" and tied to a permanent name, whereas a lambda is defined "on the fly" in an "expression" and has no permanent name.
    • Lambdas can be used with .NET expression trees, whereas methods cannot.

🔗 Source: stackoverflow.com

Q24: Could you explain the difference between Func vs. Action vs. Predicate?

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

  • Predicate: essentially Func<T, bool>; asks the question "does the specified argument satisfy the condition represented by the delegate?" Used in things like List.FindAll.
  • Action: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.
  • Func: Used extensively in LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.

🔗 Source: stackoverflow.com

Q25: Implement the "Where" method in C

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

Consider:

public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Predicate< T> prodicate)
{
  foreach(var item in items)
  {
      if (predicate(item))
      {
           // for lazy/deffer execution plus avoid temp collection defined
           yield return item;
      }
  }
}

Enter fullscreen mode Exit fullscreen mode

🔗 Source: medium.com

Q26: Explain what is weak reference in C#?

Topic: C#
Difficulty: ⭐⭐⭐⭐⭐

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.

Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

🔗 Source: docs.microsoft.com

Q27: Name some disadvantages of LINQ over sprocs

Topic: LINQ
Difficulty: ⭐⭐⭐⭐⭐

Some disadvantages of LINQ vs sprocs:

  1. Network traffic: sprocs need only serialize sproc-name and argument data over the wire while LINQ sends the entire query. This can get really bad if the queries are very complex. However, LINQ's abstraction allows Microsoft to improve this over time.
  2. Less flexible: Sprocs can take full advantage of a database's featureset. LINQ tends to be more generic in it's support. This is common in any kind of language abstraction (e.g. C# vs assembler).
  3. Recompiling: If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly. Sprocs can sometimes allow a DBA to tune the data access routine without a need to redeploy anything.

Security and manageability are something that people argue about too.

  1. Security: For example, you can protect your sensitive data by restricting access to the tables directly, and put ACLs on the sprocs. With LINQ, however, you can still restrict direct access to tables and instead put ACLs on updatable table views to achieve a similar end (assuming your database supports updatable views).
  2. Manageability: Using views also gives you the advantage of shielding your application non-breaking from schema changes (like table normalization). You can update the view without requiring your data access code to change.

🔗 Source: stackoverflow.com

Thanks 🙌 for reading and good luck on your interview!
Please share this article with your fellow devs if you like it!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player