C# Interview Questions


This article summarizes the list of basic C# interview question which I came across during the interviews. This has helped me to crack the interviews.

What are the different ways to pass parameters to a method in C#?

There are 3 ways in which parameters can be passed to the method in C#
Value Parameters: A value is passed as a parameter to the method. Any change in the value of the method does not change the value of the argument.
Reference Parameters: This can be achieved by using the ref keyword. In this the value is not passed but the reference(pointer to the memory location) is passed to the method. Any change in the value of the method changes the value of the argument.
Output Parameters: Out parameter is used to return more then one value from the method. In this reference is passed to the out parameter.

What is the difference between dynamic type variables and Object Type variables in C#

The difference is basically in type checking during program lifecycle. Dynamic type is checked during runtime and Object Type is checked during compile time.

What is Anonymous Type and Dynamic Types in C#?

Anonymous type is a class type which provide a good way to encapsulate properties and method in a single object. The type name is generated by the compiler and cannot be changed at the source code level

eg: 

	var obj = new { Name = "John", Age = "10" };
     Console.WriteLine(obj.Name + obj.Age);
 

Dynamic type is a static type The dynamic type is a static type object, but will resolve all method / property / operator etc calls at runtime via the DLR or other provider (such as reflection).

eg: 

	dynamic dyn = new ExampleClass()
     dyn.method();
 

What is the difference between Anonymous Type and Dynamic types in C#?

  1. Anonymous types are proper static-typed, type-checked beasts during compile time. 
  2. Additionally, anonymous types can be handled exclusively by the compiler; 
  3. There is no type checking at compile time with dynamic
  4. dynamic requires extensive runtime support.This means type is evaluated in the runtime and not in compile time

What is Nullable Type in C#?

  1. The Nullable type allows you to assign a null value to a variable. 
  2. Nullable types can only work with Value Type not with Reference Type because it already contains a null value.
  3. Nullable type is an instance of  System.Nullable<T> struct Where T is is type and can have non nullable value types like (integer, string) 

eg: 

    //Valid declaration	
     Nullable<int> i = null;
 
     //OR
 
     int? i = null;	 

What is the difference between is and as operator in c#?

  1. is operator is used to check the compatiblity type during runtime. as operator is used for conversion between compatible types and nullable types 
  2. is operator is a boolean type and return true if type matches. as operator returns object if type matches.
  3. is operator is used for only reference type for boxing and unboxing. as operator is used for nullable refernce and boxing type conversion.

What is the difference between String and StringBuilder in c#?

String belongs to System namespace. String is immutable. Value cannot be changed it once it is created. Any change to the string will allocate a new memory returning new instance. This is not efficient for multiple string operations. 

StringBuilder belongs to System.Text namespace. StringBuilder is mutable if we need to do any string operation it will update the existing instance value and will not return the new instance. making it more efficient for lot of string operations in c#

So performance-wise StringBuilder is efficient as it not occupies more memory space.

What is Managed and Unmanaged Code in C#?

Managed code in C# and VB.Net is executed by Common Language Runtime(CLR or .Net Runtime). The lifecycle like object creation, memory allocation and object disposal is managed by runtime.

The code that is developed outside .Net Framework is known as unmanaged code. Programs that are not executed by CLR are called unmanaged code. applications developed in C, C++ are some examples of unmanaged code.

Object creation, execution and disposal of unamanaged code is handled by the developer. Any bad code may lead to memory leaks and unwanted memory allocations. Wrapper classes needs to be created to integrate unamanaged code in C#

What is Boxing and Unboxing in C#?

Boxing and Unboxing are used for type conversions.
Boxing is converting value type into object type or any interface type. This is an implicit conversion.
Unboxing is the conversion of object type into value type. This is an explicit conversion

Example of Boxing and unboxing

eg: In the following example integer i is boxed and assigned to object o

    //boxing
     int i = 23;
     object o = i;
     Console.WriteLine(i);
     Console.WriteLine(o);

eg: In below example o is unboxed and assigned to integer variable i

    //unboxing	
     i = (int) o;
     Console.WriteLine(i);
     Console.WriteLine(o);

What is the difference between continue and break statements in C#? 

continue statement skips one iteration in the while, do, for loops. break statement exits the loop.

continue example

    //continue example
 
class Example
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i < 9)
{
continue;
}
Console.WriteLine(i);
}

Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/*
Output:
9
10 */ 
//break example class BreakTest { static void Main() { for (int i = 1; i <= 100; i++) { if (i == 5) { break; } Console.WriteLine(i); } // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: 1 2 3 4 */

What is IEnumerable<T> in C#?

IEnumerable belongs to System.Collections.Generic. It has a single method GetEnumerator which exposes enumerator (IEnumerator). Which allows simple iteration over a collection of specified type.
IEnumerable is forward only.

What is IQueryable<T> in C#?

The IQueryable provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

The IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

When to use IEnumerable<T> and IQueryable<T> in C#?

IEnumerable is best suitable for working with in-memory collection like Linq to Object and Linq to xml queries. IEnumerable doesn’t move between items, it is forward only collection.

IQueryable: IQueryable belongs to System.Linq namespace. IQueryable best suits for remote data source, like a database or web service (or remote queries). IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).

So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable

What is late binding and early binding in C#?

early binding happens at compile time and the compiler has the knowledge about the type and all it's members, and late binding happens at run time, the compiler doesn't know anything about the type and it's members. 

earlybinding eg: ComboBox cboItems; here compiler knows its a combobox
latebinding eg: Object obj; obj = CreateObject("assemblyname");

What is the difference between Virtual method and abstract method?

Virtual Function/Method:
  1. It can be declared inside abstract as well as non abstract class.
  2. It contains method implementation.
  3. It can be overridden in derived.
  4. Overriding method must contain virtual keyword 
Abstract Function/Method:
  1. It can be declared only inside abstract class.
  2. It contains only method declaration not the implementation in abstract class.
  3. It must be overridden in derived class.
Stackoverflow

What is the Constructor Chaining in C#?

Constructor Chaining is an approach where a constructor calls another constructor in the same or base class.

Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our case id). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

This time, we only assign values in one constructor which consists of the most number of parameters. And we call that constructor when the other two constructers are called.

eg:
    class Student { string _studentType = ""; string _id = ""; string _fName = ""; string _lName = ""; public Student(string id) : this(id, "", "") { } public Student(string id, string fName) : this(id, fName, "") { } public Student(string id, string fName, string lName) { //Validate logic..... _studentType = "<student_type>"; _id = id; _fName = fName; _lName = lName; } }
 
Reference

What is shallow copy and deep copy?

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.  


What’s the difference between the Array.CopyTo() and Array.Clone()?

Clone() is used to copy only structure of data/array it doesn't copy the actual data. (shallow copy)
CopyTo() copies the structure as well as actual data. (deep copy)

Can Multiple Catch Blocks be executed in C#?

No only single catch block gets executed

What is Singleton Design Pattern?

Singleton is one of the simplest design pattern. This pattern ensures that class has only one instance during the application lifecycle.

When to use it?

  1. Exactly one instance of a class is required.
  2. Controlled access to a single object is necessary.

Difference between Throw Exception and Throw Clause?

What are delegate in C#?

  1. A delegate is a type that references to the method with a parmaters and return type. 
  2. Delegates are similar to C++ function pointers, but delegates are fully object-oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method.
  3. Delegates allow methods to be passed as parameters.
  4. Delegates can be used to define callback methods.
  5. Event handlers are nothing but methods invoked by delegates.
  6. Delegates can be chained together; for example, multiple methods can be called on a single event.

What is Anonymous methods?

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

You can use a lambda expression or an anonymous method to create an anonymous function. We recommend using lambda expressions as they provide more concise and expressive way to write inline code. Unlike anonymous methods, some types of lambda expressions can be converted to the expression tree types.

What is a multicast delegate in C#?

A multicast delegate is a delegate that holds references to more then one function. When we invoke multicast delegate all the functions referenced will be invoked by the delegates.

Multicast delegates is one of the feature of delegates, it wraps the reference of multiple methods and calls it sequentially and it is also known as Delegate Chaining.
       
// Declare Delegates
     public delegate void MultiCast(int num1, int num2);
 
     class Program
     {
         public void Add(int num1, int num2)
         {
             Console.WriteLine(num1 + num2);
         }
         public  void Sub(int num1, int num2)
         {
             Console.WriteLine(num1 - num2);
         }
         public  void Mul(int num1, int num2)
         {
             Console.WriteLine(num1 * num2);
         }
 
         static void Main(string[] args)
         {
             MultiCast del1, del2, del3, multAddDel, multSubDel;
             del1 = new Program().Add;
             del2 = new Program().Sub;
             del3 = new Program().Mul;
 
         //`There are three ways to define the multicast delegate.`
 
             //1 way
 
             //Adding delegates 
             multAddDel = del1 + del2 + del3;
             multAddDel(10, 10);
             //Removing Delegates
             multSubDel = multAddDel - del3;
             multSubDel(10, 10);
 
             Console.WriteLine();
             Console.WriteLine("Second Way");
 
             //2 way
 
             MultiCast multAddDel1 = null;
             //Adding delegates 
             multAddDel1 += del1;
             multAddDel1 += del2;
             multAddDel1 +=  del3;
             multAddDel1(10, 10);
             //Removing Delegates
             multAddDel1 -= del3;
             multAddDel1(10, 10);
 
             Console.WriteLine();
             Console.WriteLine("Third Way");
 
             //3 way
 
             MultiCast multAddDel2 = null;
             //Adding delegates 
             multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del1);
             multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del2);
             multAddDel2 = (MultiCast)Delegate.Combine(multAddDel2, del3);
             multAddDel2(10, 10);
 
             //Removing Delegates
             multAddDel2 = (MultiCast)
                 Delegate.Remove(multAddDel2, del3);
 
             multAddDel2(10, 10);
             Console.ReadLine();
         }
     }
Stackoverflow MSDN More Reference

Difference between the Equality Operator (==) and Equals() Method in C#
What are Different Ways a Method can be Overloaded?
What are Generics in C#?
What are Value types and Reference types in C#?

What is the difference between const and readonly in C#?

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared.public class 

MyClass { public const double PI1 = 3.14159; }

A readonly member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor, as well being able to be initialized as they are declared.

public class MyClass1 { 
 public readonly double PI2 = 3.14159; 
 //or public readonly double PI3; 
 public MyClass2() 
 { PI3 = 3.14159; } 
}

const
  • They can not be declared as static (they are implicitly static)
  • The value of constant is evaluated at compile time
  • constants are initialized at declaration only

readonly
  • They can be either instance-level or static
  • The value is evaluated at run time
  • readonly can be initialized in declaration or by code in the constructor

Comments