In this article, you will be seeing frequently asked C# programming interview questions with answers, from developers or students, we will start with basic questions and then we will see more advanced questions.

What is C#?

C# is a programming language developed by Microsoft, which is based on OOP (Object Oriented Programming) principles and run on .NET framework, using which we can create web-applications, XML web services, windows applications etc.

Describe basic construction of C# program?

A typical C# program consists of a namespace declaration, a class, methods, attributes, a main method, statements, expressions, and comments. Consider the sample program which prints "Hello World" in C#

using System;

namespace HelloWorldApplication
{
   public class HelloWorld
   {
      public static void Main(string[] args)
      {
         Console.WriteLine("Hello World");
      }
   }
}

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

"break" is used to jump out of the current loop and execute the next statement after current loop. Read more

"continue" is used to skip the current iteration of loop and continue next iteration of loop. Read more

Mention all ways to pass parameters to method in C#?

There are three ways to pass paramters to a method in C#, here are all three ways explained:

  • Value Parameters: Passing a parameter to a method by value creates a new storage location for the value parameter. Passing parameters by value is the default type for passing parameters to the method. The value parameter is defined by specifying the data type followed by the variable name.
  • Reference Parameters: Passing a parameter to a method by reference can be achieved by using the ref keyword. Instead of passing value, we will be passing reference, that is, memory location of the variable, the method accesses the memory location of the argument and passes it as a parameter. Changes made to the parameter will also affect the argument.
  • Output Parameters:The out keyword allows a method to return two values from a function. It's similar to passing a reference parameter, except in this case data is being transferred out of the method.

Read: C# Methods

What is boxing and unboxing in C#?

When a value type is converted into object type then this implicitly conversion process is called boxing. On the other hand when an object type is converted back to its value type explicitly then it is called as unboxing.

Example:

Boxing

int x = 5;

// converting value x is boxed
object o = x; 

Unboxing

int b =(int)o; // object is converted to int (unboxing)

What is operator overloading in C#?

Most of the built-in operators available in C# can be overloaded or redefined using the operator keyword. The sample code below depicts the syntax used to implement the addition operator (+) for a user-defined class.

public static Rectangle operator+ (Rectangle b, Rectangle c)
{
   Rectangle rectangle = new Rectangle();
   rectangle.length = b.length + c.length;
   rectangle.breadth = b.breadth + c.breadth;
   rectangle.height = b.height + c.height;
   return rectangle;
}

What is difference between struct and class?

  • Struct are value type and are stored on stack, while Class are reference type and are stored on heap.
  • Struct "do not support" inheritance, while class supports inheritance. However struct can implements interface.
  • Instances of classes are created by using the new operator while Instances of structs can also be created by using the new operator, but this is not required.
  • classes are used for complex and large set data. structs are simple to use

What is a constructor?

Constructor is a special method in C# class, which has same name as it's class name and it is invoked when a object is created.

It is used when we initialize an object of a class. It looks like similar to method but it has the same name as a class.

//class declared
public class ClassName{

   //contructor
   public ClassName(){
     //do something
   }
}

Read more: C# Constructors and Destructors

What is a namespace in C#?

The namespace keyword is used to declare a scope. The ability to create scopes within your project helps organize code and lets you create globally-unique types.

The namespace is collection of same set of related objects or same set of types.

All namespaces are implicitly public and you cannot change this behavior. A namespace declaration does not support modifiers or attributes.

namespace MyNamespace
{
    class MyClass { }

    namespace MyNamespace.NestedNamespace
    {
        class Employee { }
    }
}

The fully qualified name is indicated as a comment following each entity.

namespace M1     // M1
{
    class C1      // M1.C1
    {
        class C2   // M1.C1.C2
        {
        }
    }
    namespace M2  // M1.M2
    {
        class C2   // M1.N2.C2
        {
        }
    }
}

Why are strings in C# immutable?

The immutable meaning is unchanging over time or unable to be changed.

Immutable string cannot be changed once declared and defined. In a simple word, if we declare a string for example, string str = "qa", a memory will be allocated for it and "qa" string will be placed in the memory.

If we try to change the value of string pointed by str variable with, for example, str = "qa with experts", an another new memory will be created and "qa with experts" string will be placed in it.

Now, str variable will no longer point the memory where string “interview” was placed and old memory will be destroyed by Garbage collection.

Can we specify the accessibility modifier for methods inside the interface?

All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

How exception handling is implemented in C#?

Exception handling is implemented in C# using try-catch block.

We use try and catch to handle errors in C#. The code which we want to execute is written inside try. If the statements inside the try have any error, then the statement inside the catch block is executed.

Example:

public static void Main(string[] args)
  {
    try
    {
      int a = 2;
      int b = 0;
      int c = a/b;

      Console.WriteLine(c);
    }
    catch(Exception e)
    {
      Console.WriteLine(e);
    }
  }
  • try – Contains a block of code for which an exception will be checked.
  • catch – It is a program that catches an exception with the help of exception handler.
  • finally – It is a block of code written to execute regardless whether an exception is caught or not.
  • Throw – Throws an exception when a problem occurs.

Read more: Exception handling in C# (Try-catch-finally block)

How do you initiate a string without escaping each backslash?

You can put "@" sign before the string, for example

//regular string literal.
string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";

// verbatim string literal ( @ before string)
string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";

Is it possible to return multiple value from a function in C#?

Yes, it is possible, we can return multiple values from a function using the following approaches:

  • Reference parameters
  • Output parameters
  • Returning an Array
  • Returning a tuple

Example:

public int[] MultipleValueReturns(int a, int b)  
{  
      int []minMax = int[2];  
      if(a>b)  
      {  
           minMax[0] = a;  
           minMax[1] = b;  
      }  
      else  
      {  
           minMax[0] = b;  
           minMax[1] = a;  
      }  
      return minMax;  
}  

What is the difference between interface and class in C#?

The basic difference is that a class has both a definition and an implementation whereas an interface only has a definition. Interfaces are actually implemented via a class.

Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members.

A class generally implements the methods defined in an interface.

What is Delegates in C#?

Delegates contains the reference to several methods and call them when needed. So, you create numbers of methods as you need and attach it to delegates. At runtime, an event gets fired and delegates dynamically call the function and show the result.

using System;
					
    public class DelegateTest
    {
        //Declaration
        //Creating Delegates with no parameters and no return type.
        public delegate void FirstDelegate();
 
        public void funtion1()
        {
            Console.WriteLine("I am Function 1");
        }
        public void funtion2()
        {
            Console.WriteLine("I am Function 2");
        }
        
    }
 
    public class Program
    {
       public static void Main(string[] args)
        {
            DelegateTest testdelegate = new DelegateTest();
            //Instantiation
            DelegateTest.FirstDelegate fd1 = new DelegateTest.FirstDelegate(testdelegate.funtion1);
            DelegateTest.FirstDelegate fd2 = new DelegateTest.FirstDelegate(testdelegate.funtion2);            
 
          //Invocation 
            fd1();
            fd2();
                     
        }
    }

Output:

I am Function 1
I am Function 2

delegate-in-csharp-example-min.png

Read More: Delegates in C#

What is difference between constants and readonly in C#?

const: it can't be changed anywhere, and they are static by default

readonly: This value can only be changed in the constructor. can't be changed in normal functions and are evaluated when instance is created.

How does C# handle encapsulation?

Encapsulation is handled in C# using access modifiers, by using public, private and protected access specifiers in C#, we can implement how a class will be accessed and from where.

  • public: class, variable etc can be accessed from anywhere in application, means variables inside class can be accessed by outside of class.
  • private: class, variable etc can only be accessed by same class members, and variables, functions etc cannot be accessed by any member outside of class
  • protected: access specifier allows a child class to access the member variables and member functions of its base class

What is the difference between an interface and abstract class?

Interfaces have all the methods having only declaration but no definition. In an abstract class, we can have some concrete methods. In an interface class, all the methods are public. An abstract class may have private methods.

What are some of the features of generics in C#?

Here are some of the features of generics:

  • They make C# code reusable, type safe, and performance optimized.
  • They allow the developer to create generic classes, methods, events, delegates, and interfaces.
  • They allow the developer to create generic collection classes in the System.Collections.Generic namespace.
  • You may get information on the types used in a generic data type at run-time by means of reflection