C# Interview Questions

C# Interview Questions and Answers,You Need To Know

This article is mainly focused on the most repeatedly asked and the latest updated C# interview questions that are appearing in most of the current C# interviews.

If you are looking for “C# interview questions” or  “advanced c# interview questions, then you at the right place. Previously I have created a list of C interview questions, C++ interview questions and many more that are liked by many people. I have got the response to create a list of C# interview questions for experienced and fresher developer. So here I have tried to create some collection of “C# sharp interview questions with answer” that might ask by your interviewer.  I hope these C sharp interview questions with answer will be helpful.

Q) What is C#?

C# is an object-oriented, type-safe computer programming language. It was developed by Microsoft led by Anders Hejlsberg and his team within the .Net initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).

C# pronounced as “C sharp” and compiled by the .Net framework to generate Microsoft Intermediate Language. C# is a lot similar to Java syntactically and is easy for the users who have knowledge of C, C++ or Java.

It can be used to develop all kinds of software targeting various platforms including Windows, Web, and Mobile using just one programming language. We can say, C# is one of the most popular programming languages in the world and used by many software developers to build all kinds of software.

 

Q) What is an object?

An object is the basic concepts of Object-Oriented programming language. It is an instance of a class through which we access the methods and attributes of that class. “New” keyword is used to create an object. A class that creates an object in memory will contain the information about the methods, variables, and behavior of that class.

 

 Q) What are C# attributes and their significance?

C# provides developers a way to define declarative tags on certain entities, eg. Class, method, etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.

 

Q) What is the meaning of instantiation?

The act of creating an object is called instantiation. Using the blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint.

 

Q) How will you differentiate between a Class and a Struct?

In .NET, there are two categories of types, reference types and value types. Although both class and structure are user-defined data types, they are different in several fundamental ways. A class is a reference type and Struct is a value type.

The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

While the structure doesn’t support inheritance and polymorphism, the class provides support for both. A class can be of an abstract type, but a structure can’t.

All members of a class are private by default, while members of a struct are public by default. Another distinction between class and struct is based on memory management. The former supports garbage collection while the latter doesn’t.

 

Q) What is the difference between public, static, and void?

public: A public declared variables or methods are accessible anywhere in the application.

static: A static declared variables or methods are globally accessible without creating an instance of the class. A static member is by default not globally accessible it depends upon the type of access modified used. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.

void: A void is a type of modifier that states that the method or variable does not return any value.

 

Q) What’s a multicast delegate?

A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.

 

Q) How do I calculate someone’s age in C#?

You can calculate your age using below C# program.

// C# program for age calculator
using System;

class CALAGE
{
    public static void CalculateAge(DateTime DayOfBirth)
    {
        var dt = DateTime.Now;
        var years = new DateTime(DateTime.Now.Subtract(DayOfBirth).Ticks).Year - 1;
        var pastYear = DayOfBirth.AddYears(years);
        var months = 0;
        for ( int i = 1; i <= 12; i++)
        {
            if (pastYear.AddMonths(i) == dt)
            {
                months = i;
            }
            else if (pastYear.AddMonths(i) >= dt)
            {
                months = i - 1;
                break;
            }
        }

        var days = dt.Subtract(pastYear.AddMonths(months)).Days;

        Console.WriteLine(string.Format("It's been {0} years, {1} months, and {2} days since your birthday", years,months, days));
    }
    // driver code to check the above function
    public static void Main()
    {

        DateTime dob = Convert.ToDateTime("1989/04/27");
        CalculateAge(dob);
    }
}

 

 

Q) What is the difference between public static, public and static methods?

public: public by itself means this is an instance-based member that is accessible to external callers (those with access to the type itself).

static: static by itself means the member is not instance-based. You can call it without needing any particular instance (or even any instance at all). Without an accessibility qualifier, non-public is assumed – so the member will not be accessible to external callers.

public static: public static is a static method that is accessible to external callers.

 

Q) What is a Virtual Method in C#?

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method’s basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence, it is also an example of polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member if no derived class has overridden the member.

Virtual Method:

  • By default, methods are non-virtual. We can’t override a non-virtual method.
  • We can’t use the virtual modifier with static, abstract, private or override modifiers.

 

Q) List down the fundamental OOP concepts?

There are four fundamental OOP (Object Oriented Programming) concept they are listed as follows:

  • Inheritance-  Ever heard of this dialogue from relatives “you look exactly like your father/mother” the reason behind this is called ‘inheritance’. From the Programming aspect, It generally means “inheriting or transfer of characteristics from parent to child class without any modification”. The new class is called the derived/child class and the one from which it is derived is called a parent/base class.
  • Polymorphism- You all must have used GPS for navigating the route, Isn’t it amazing how many different routes you come across for the same destination depending on the traffic, from a programming point of view this is called ‘polymorphism’. It is one such OOP methodology where one task can be performed in several different ways. To put it in simple words, it is a property of an object which allows it to take multiple forms.
  • Encapsulation- In a raw form, encapsulation basically means binding up of data in a single class.A class shouldn’t be directly accessed but be prefixed in an underscore.
  • Abstraction- Suppose you booked a movie ticket from bookmyshow using net banking or any other process. You don’t know the procedure of how the pin is generated or how the verification is done. This is called ‘abstraction’ from the programming aspect, it basically means you only show the implementation details of a particular process and hide the details from the user. It is used to simplify complex problems by modeling classes appropriate to the problem.An abstract class cannot be instantiated which simply means you cannot create objects for this type of class. It can only be used for inheriting the functionalities.

 

Q) Compare Virtual methods and Abstract methods.

Any Virtual method must have a default implementation, and it can be overridden in the derived class using the override keyword. On the contrary, an Abstract method doesn’t have an implementation, and it resides in the abstract class. The derived class must implement the abstract method. Though not necessary, we can use an override keyword here.

public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

 

Q) What are Namespaces in C#?

The use of namespaces is for organizing large code projects. The most widely used namespace in C# is System. Namespaces are created using the namespace keyword. It is possible to use one namespace in another, known as Nested Namespaces.

 

Q) Is every abstract function virtual in C#, in general?

Yes, When an instance method declaration includes an abstract modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.

 

Q) What are I/O classes in C#? Define some of the most commonly used ones.

The System.IO namespace in C# consists of several classes used for performing various file operations, such as creation, deletion, closing, and opening. Some of the most frequently used I/O classes in C# are:

File – Manipulates a file
Path – Performs operations related to some path information
StreamReader – Reads characters from a stream
StreamWriter – Writes characters to a stream
StringReader – Reads a string buffer
StringWriter – Writes a string buffer

 

Q) What is the difference between SessionState and ViewState?

There are the following differences between the session state and ViewState.

  • Session state is saved on the server, ViewState is saved in the page.
  • An important point that the ViewState travels up and down between client and server, but SessionState stays on the server.
  • Session state is usually cleared after a period of inactivity from the user (no request happened containing the session id in the request cookies).
  • The view state is posted on subsequent posts back in a hidden field.

 

Q) What’s the difference between a method and a function?

Here,  I am giving a simplified explanation, ignoring issues of scope, etc.

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

A method is implicitly passed the object on which it was called.
A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data).

 

Q) What is the difference between an abstract function and a virtual function?

Abstract function:

An abstract function cannot have functionality. You’re basically saying, any child class MUST give their own version of this method, however, it’s too general to even try to implement in the parent class.

Virtual function:

A virtual function is basically saying look, here’s the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.

 

Q)What is an interface class? Give one example of it

An Interface is an abstract class which has only public abstract methods, and the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

There are few properties of the interface class,

  • Interfaces specify what a class must do and not how.
  • Interfaces can’t have private members.
  • By default, all the members of Interface are public and abstract.
  • The interface will always be defined with the help of the keyword ‘interface‘.
  • An interface cannot contain fields because they represent a particular implementation of data.
  • Multiple inheritances are possible with the help of Interfaces but not with classes.

Syntax for Interface Declaration:

interface  <interface_name >
{
    // declare Events
    // declare indexers
    // declare methods 
    // declare properties
}

 

Syntax for Implementing Interface:

class class_name : interface_name

 

Sample Example Code,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 interface ISampleInterface
 {
  void SetTutorial(int pID, string pName);
  String GetTutorial();
 }

 class ImplementationClass  : ISampleInterface
 {
  protected int TutorialID;
  protected string TutorialName;

  public void SetTutorial(int pID, string pName)
  {
   TutorialID = pID;
   TutorialName = pName;
  }

  public String GetTutorial()
  {
   return TutorialName;
  }

  static void Main(string[] args)
  {
   ImplementationClass  pTutor = new ImplementationClass ();

   pTutor.SetTutorial(1,"C# interview Questions by Aticleworld.com");

   Console.WriteLine(pTutor.GetTutorial());

   Console.ReadKey();
  }
 }
}

 

Q) What is the advantage of interface class?

There are the following advantages of the interface.

  • It is used to achieve loose coupling.
  • It is used to achieve total abstraction.
  • To achieve component-based programming
  • To achieve multiple inheritance and abstraction.
  • Interfaces add a plug and play like architecture into applications.

 

Q) Explain the process of inheriting a class into another class?

Colon is used as an inheritance operator in C#. Place the colon and the class name.

public class Derivedclass: childclass

 

Q) 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.

There are some differences between an interface and an abstract class that I have arranged in a table for easier comparison:

ABSTRACT CLASS INTERFACE
It contains both declaration and definition part. It contains only a declaration part.
Multiple inheritances are not achieved by an abstract class. Multiple inheritances are achieved by an interface.
It contains a constructor. It does not contain a constructor.
It can contain static members. It does not contain static members.
It can contain different types of access modifiers like public, private, protected, etc. It only contains public access modifier because everything in the interface is public.
The performance of an abstract class is fast. The performance of the interface is slow because it requires time to search the actual method in the corresponding class.
It is used to implement the core identity of the class. It is used to implement the peripheral abilities of the class.
A class can only use one abstract class. A class can use multiple interfaces.
If many implementations are of the same kind and use common behavior, then it is superior to use an abstract class. If many implementations only share methods, then it is superior to use Interface.
An abstract class can contain methods, fields, constants, etc. An interface can only contain methods.
It can be fully, partially or not implemented. It should be fully implemented.

 

Q) What are circular references?

A circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

 

Q) What is the advantage of abstract class?

The advantages of an abstract class are:

  • Ability to specify default implementations of methods.
  • Added invariant checking to functions.
  • Have slightly more control in how the “interface” methods are called.
  • Ability to provide behavior-related or unrelated to the interface for “free”

 

Q)What happens if the inherited interfaces have conflicting method names?

If we implement multiple interfaces in the same class with conflict method names, we don’t need to define all. In other words, we can say if we have conflict methods in the same class, we can’t implement their body independently in the same class because of the same name and same signature. Therefore, we have to use the interface name before the method name to remove this method confiscation. Let’s see an example:

interface testInterface1
{
    void Show();
}
interface testInterface2
{
    void Show();
}
class Abc: testInterface1,
    testInterface2
{
    void testInterface1.Show()
    {
        Console.WriteLine("For testInterface1 !!");
    }
    void testInterface2.Show()
    {
        Console.WriteLine("For testInterface2 !!");
    }
}
Now see how to use these in a class:
class Program
{
    static void Main(string[] args)
    {
        testInterface1 obj1 = new Abc();
        testInterface1 obj2 = new Abc();
        obj1.Show();
        obj2.Show();
        Console.ReadLine();
    }
}

Output:

For testInterface1 !!
For testInterface1 !!

 

Q) What is Constructor in C#?

In C#, a constructor is a special method whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.

Note: If you don’t provide a constructor for your class, C# creates one by default that instantiates the object and sets member variables to the default values.

The constructor in C# has the same name as class or struct. Below I am mentioning some types constructors supported by C#.

  1. Default Constructor.
  2. Parametrized Constructor.
  3. Copy Constructor.
  4. Private Constructor.
  5. Static Constructor.

An example of a constructor,

public class PersonInfoInfo
{
   private string last;
   private string first;
   
   //constructor
   public PersonInfo(string lastName, string firstName)
   {
      last = lastName;
      first = firstName;
   }
   
   // Remaining implementation of PersonInfo class.
}

 

Q) Explain some points related to the constructor?

There are some important points related to the constructor which mentioned below,

  • A class can have any number of constructors.
  • A constructor doesn’t have any return type, not even void.
  • A static constructor cannot be a parameterized constructor.
  • Constructor of a class must have the same name as the class name in which it resides.
  • A constructor can not be abstract, final, static and Synchronized.
  • Within a class, you can create only one static constructor.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

 

Q) What is difference between “is” and “as” operators in c#?

“is” operator is used to check the compatibility of an object with a given type, and it returns the result as Boolean.

“as” operator is used for casting of an object to a type or a class.

 

Q) Why can’t you specify the accessibility modifier for methods inside the interface?

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

 

 Q) What are Value types and Reference types in C#?

In C#, data types can be of two types, value types, and reference types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently operate on their values, Value type data types are stored on a stack and reference data types are stored on a heap.

In C#, basic data types include int, char, bool, and long, which are value types. Classes and collections are reference types.

 

Q) What are Jagged Arrays?

A jagged array is an array of arrays such that member arrays can be of different sizes. The elements of Jagged array are reference types and initialized to null by default. A jagged array can also be mixed with multidimensional arrays.

Syntax of the jagged Arrays:

data_type[][] Array_Name = new data_type[rows][]

In Jagged arrays, the user has to provide the number of rows only.

 

Q) Is elements of jagged array must be initialized before its use.

Yes, the elements of a Jagged Array must be initialized before its use.

 

Q) Why Doesn’t C# Allow Static Methods to Implement an Interface?

You can’t define static members on an interface in C#. An interface is a contract for instances.

 

Q) What do you understand by regular expressions in C#? Write a program that searches a string using regular expressions.

A regular expression is a template for matching a set of input. It can consist of constructs, character literals, and operators. Regex is used for string parsing, as well as replacing the character string. Following code searches a string “C#” against the set of inputs from the languages array using Regex:

static void Main(strong[] args)
{
    string[] languages = {“C#”, “Python”, “Java”};
    foreach(string s in languages)
    {
        if(System.Text.RegularExpressions.Regex.IsMatch(s,“C#”))
        {
            Console.WriteLine(“Match found”);
        }
    }
}

 

 

Q) What is the difference between ref & out parameters?

Both ref and out are used to pass the arguments in the function. The main difference between ref and out is that a variable you pass as an out parameter doesn’t need to be initialized but passing it as a ref parameter it has to be set to something.

Example,

int a;
Test(out a); // OK

int b;
Test(ref b); // Error: b should be initialized before calling the method

 

There are some differences between a ref and an out that I have arranged in a table for easier comparison:

REF KEYWORD OUT KEYWORD
The parameters must initialize before it passes to ref. It is not necessary to initialize parameters before it passes to out.
It is not necessary to initialize the value of a parameter before returning to the calling method. It is necessary to initialize the value of a parameter before returning to the calling method.
The passing of value through the ref parameter is useful when the called method also needs to change the value of the passed parameter. The declaring of parameter throughout parameter is useful when a method returns multiple values.
When the ref keyword is used the data may pass in bi-directional. When out keyword is used the data only passed in unidirectional.

 

 

Q)What is the difference between var and dynamic in C#

var keyword:

The var keyword was introduced in C# 3.0 and variables declared with var are statically typed. Here, the type of variable declared is decided at the compile time. Variables that are declared as var should be initialized at the time of declaration. By looking at the assigned value, the compiler will decide the variable type. As the compiler knows the data type of the variable at compile-time, errors will be caught at that time only. And Visual Studio 2008 and later versions will show the IntelliSense for var type.

Example,

var obj "aticleworld.com";

In the above sentence, obj will be treated as a string

obj = 20;

In the above line, the compiler will throw an error, as the compiler already decided the type of obj as String and assigned an integer value to string variable violating safety rule type.

dynamic keyword:

The dynamic keyword was introduced in C# 4.0 and variables declared with dynamic were dynamically typed. Here, the type of variable declared is decided at runtime. Variables that are declared as dynamic don’t need to initialize the time of declaration. The compiler won’t know the variable time at the time of compiling, hence errors can’t be caught by the compiler while compiling. IntelliSense is not available since the type of variable will be decided at runtime.

Example,

dynamic obj = "aticleworld";

In the above code, obj will be treated as a string.

obj = 20;

The compiler will not throw any error, though obj is assigned to the integer value. The compiler will create the type of obj as String and then it recreates the type of obj as an integer when we assign an integer value to obj.

 

 

If you like online courses, we have selected some good C# courses for you from the best learning platform. 

 

 

Q) What is the use of ‘using’ statement in C#?

The ‘using’ block is used to obtain a resource and process it and then automatically dispose of when the execution of the block completed.

In simple words, The reason for the using statement is to ensure that the object is disposed of as soon as it goes out of scope, and it doesn’t require explicit code to ensure that this happens.

Example,

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

 

 

Q) What is the major use of ‘using’ keyword?

The using keyword has three major uses:

  1. The using statement defines a scope at the end of which an object will be disposed.
  2. The using directive creates an alias for a namespace or imports types defined in other namespaces.
  3. The using static directive imports the members of a single class.

 

Q) What is the difference between String and string in C#?

Many C# programmers ask is: “What is the difference between string and String?” Basically string is an alias in C# for System.String. So technically, there is no difference.

In simple words, “string” is a datatype, whereas “String” represents a class. As far as guidelines, it’s generally recommended to use string any time you’re referring to an object.

There is another small difference is that if you use the String class, you need to import the System namespace on top of your file, whereas you don’t have to do this when using the string keyword.

Example,

string name= "aticleworld";

 

 

Q)What is function overloading?

A function Overloading is a common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures (types and number of arguments in the argument list).

Note: You cannot overload function declarations that differ only by return type.

 

Q) Explain some ways of doing overloading function in C#

Function overloading can be done by changing:

  • The number of parameters in two functions.
  • The data types of the parameters of functions.
  • The order of the parameters of functions.

 

Q) Explain Inheritance in C# with an example?

Inheritance allows us to define a class that inherits all the methods and attributes from another class. The class that inherits from another class is called a derived class or child class. The class from which we are inheriting is called parent class or base class.

There are many benefits of inheritance in C#, so let us see them:

  • Inheritance provides code reusability, makes it easier to create and maintain an application. So we don’t have to write the same code again and again.
  • It allows us to add more features to a class without modifying it.
  • It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
  • Inheritance represents real-world relationships well.

 

Q) What is serialization?

When we want to transport an object through a network, then we have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called Serialization. For an object to be serializable, it should implement ISerialize Interface. De-serialization is the reverse process of creating an object from a stream of bytes.

 

Q) What is the best way to give a C# auto-property an initial value?

In C# 5 and earlier, to give auto-implemented properties an initial value, you have to do it in a constructor. Let see an example,

using System;

class Person
{
    public Person()
    {
        //do anything before variable assignment

        //assign initial values
        Name = "Aticleworld.com";

        //do anything after variable assignment
    }
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        var Person = new Person();

        Console.WriteLine(Person.Name);
    }
}

Output:

Aticleworld.com

 

Since C# 6.0, you can specify the initial value in-line. See the below code,

using System;

class Person
{
    public string Name { get; set; } = "Aticleworld.com";
}

class Program
{
    static void Main()
    {
        var Person = new Person();

        Console.WriteLine(Person.Name);
    }
}

Output:

Aticleworld.com

 

Q) List down the reason behind the usage of C# language.

There are several reasons for the usage of C# as a programming platform. Some of them are listed below.

  • C# is popular because easy to learn anybody learn C# quickly.
  • Rich library, you can get almost all the things.
  • It has great support and there are many supporting platforms.
  • Component oriented language.
  • Follows a Structured approach.
  • Produces readable and efficient programs.
  • Once written can be compiled on different platforms.

 

Q) What are Custom Exceptions?

Sometimes there are some errors that need to be handled as per user requirements. Custom exceptions are used for them and are used as defined exceptions.

 

Q) What is Managed or Unmanaged Code?

Managed Code:

The code, which is developed in the .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 the .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.

 

Q) Explain the features of C#?

There are several features supported in C#. Some of them are listed below.

  • Use of Constructors and Destructors.
  • Easy to learn.
  • General Purpose and Object-Oriented.
  • Structured language.
  • Platform independent for compilation.
  • Part of .NET framework.
  • XML Documentation and Indexers.

 

Q)What is the difference between constant and readonly in C#?

Const is nothing but “constant”, a variable of which the value is constant but at compile time. It’s mandatory to assign a value to it. By default, a const is static and we cannot change the value of a const variable throughout the entire program.
Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor.
In short, Constant variables are declared and initialized at compile time. The value can’t be changed afterward. Read-only is used only when we want to assign the value at run time.

Example

We have a Test Class in which we have two variables, one is read-only and the other is a constant.
class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
        cons = 100;
    }
    public void Check()
    {
        Console.WriteLine("Read only : {0}", read);
        Console.WriteLine("const : {0}", cons);
    }
}

Here, I was trying to change the value of both the variables in the constructor, but when I try to change the constant, it gives an error to change their value in the block that I have to call at run time.

ASP.NET

Finally, remove that line of code from class and call this Check() function like in the following code snippet:
class Program
{
    static void Main(string[] args)
    {
        Test obj = new Test();
        obj.Check();
        Console.ReadLine();
    }
}
class Test
{
    readonly int read = 10;
    const int cons = 10;
    public Test()
    {
        read = 100;
    }
    public void Check()
    {
        Console.WriteLine("Read only : {0}", read);
        Console.WriteLine("const : {0}", cons);
    }
}

Output:

Read only : 100
const : 10

 

Q) Can we use “this” command within a static method?

We can’t use ‘this’ in a static method because the keyword ‘this’ returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and are called with the name of a class, not by instance, so we can’t use this keyword in the body of static Methods.

 

Q) Write name of the most common places to look for a Deadlock in C#.

For recognizing deadlocks, one should look for threads that get stuck on one of the following:

  • .Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks).
  • Dispatcher.Invoke() (When working in WPF).
  • Join() (When working with Threads).
  • lock statements (In all cases).
  • WaitOne() methods (When working with.
  • AutoResetEvent/EventWaitHandle/Mutex/Semaphore)

 

Q) Explain Deadlock?

A deadlock is a situation that arises when a process isn’t able to complete it’s execution because two or more than two processes are waiting for each other to finish. This usually occurs in multi-threading. In this, a shared resource is being held up by a process and another process is waiting for the first process to get over or release it, and the thread holding the locked item is waiting for another process to complete.

 

Q) illustrate Race Condition?

A Race Condition occurs in a situation when two threads access the same resource and try to change it at the same time. The thread which accesses the resource first cannot be predicted. Let me take a small example where two threads X1 and X2 are trying to access the same shared resource called T. And if both threads try to write the value to T, then the last value written to T will be saved.

 

Q) What is Thread Pooling?

A Thread pool is a collection of threads that perform tasks without disturbing the primary thread. Once the task is completed by a thread it returns to the primary thread.

 

Q) Distinguish between finally and finalize blocks?

finally block is called after the execution of try and catch blocks, It is used for exception handling whether or not the exception has been caught this block of code gets executed. Generally, this block of code has a cleaner code.

The finalize method is called just before the garbage collection. Main priorities are to perform clean up operation for unmanaged code, it is automatically invoked when an instance is not subsequently called.

 

Q) What is Boxing and Unboxing in C#? 

Boxing and unboxing are an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object) and Pointer Types. Boxing and Unboxing both are used for type conversions.

Boxing:

The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.

Consider the following declaration of a value-type variable:

int i= 123;

// Boxing copies the value of i into object o.
Object obj = i;

 

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following image of boxing conversion:

C# Interview Questions

 

unboxing:

The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.

The following statements demonstrate both boxing and unboxing operations:

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

Below image demonstrates the result of the above-mentioned statements:

C# Interview Questions

 

Q) What is enum in C#? 

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type that is user-defined.

An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be cast.

An enum is used to create numeric constants in the .NET framework. All the members of the enum are enum type. There must be a numeric value for each enum type.

The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
Some points about enum,
  • Enums are enumerated data types in c#.
  • Enums are not for the end-user, they are meant for developers.
  • Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members is the same.
  • Enumerations (enums) make your code much more readable and understandable.
  • Enum values are fixed. Enum can be displayed as a string and processed as an integer.
  • The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
  • Every enum type automatically derives from System. Enum and thus we can use System.Enum methods on enums.
  • Enums are value types and are created on the stack and not on the heap.

 

Q) Describe Accessibility Modifiers in C#

Access modifiers are keywords used to specify the scope of accessibility of a member of a type or the type itself. For example, a public class is accessible to the entire world, while an internal class may be accessible to the assembly only. 

 

Q) What is the difference between ‘protected’ and ‘protected internal’?

There are the following difference between “protected” and “protected internal”.

Protected Member:

Protected members can be accessed only by code in the same class, or in a class that is derived from that class.

Note: Protected members are not accessible using the object in the derived class.

Protected Internal:

Protected Internal member can be accessed by any code in the assembly in which it’s declared, or from within a derived class in another assembly.

Note: Protected Internal member works as Internal within the same assembly and works as Protected for outside the assembly.

 

Q) How do short-circuited operators work?

In C# a short-circuit operator can be used in a bool expression only. it will return true and depending on the condition in the control statement.

If the short-circuit finds an operand that can reflect the result of the expression then it will stop checking the remaining operands and execute the condition true or false that is being reflected by the operand.

 

Q) What is the “volatile” keyword used for?

A  volatile keyword tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself. The compiler will then avoid any optimizations that may result in problems if the variable changes “outside of its control”.

 

Q) Why use access modifiers?

Access modifiers are an integral part of object-oriented programming. Access modifiers are used to implement the encapsulation of OOP. Access modifiers allow you to define who does or who doesn’t have access to certain features.
There are 6 different types of Access Modifiers in C#:
Modifier Description
public There are no restrictions on accessing public members.
private Access is limited to within the class definition. This is the default access modifier type if none is formally specified
protected Access is limited to within the class definition and any class that inherits from the class
internal Access is limited exclusively to classes defined within the current project assembly
protected internal Access is limited to the current assembly and types derived from the containing class. All members in the current project and all members in derived class can access the variables.
private protected Access is limited to the containing class or types derived from the containing class within the current assembly.

Q) Why do we use Async and Await in C#?

Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.

 

Q) Explain different states of a thread in C#?

A thread in C# can have any of the following states:

Aborted – The thread is dead but not stopped.
Running – The thread is executing.
Stopped – The thread has stopped the execution.
Suspended – The thread has been suspended.
Unstarted – The thread is created but has not started execution yet.
WaitSleepJoin – The thread calls sleep, calls wait on another object, and calls join on some other thread.

 

Q) What are delegates?

Delegates are the same are function pointers in C++, but the only difference is that they are type-safe, unlike function pointers. Delegates are required because they can be used to write much more generic type-safe functions.

 

Q) What is the difference between “continue” and “break” statements in C#?

break statement:

The break statement terminates the execution of the nearest enclosing loop. After termination of the loop or switch body, control passes to the statement that follows the terminated statement.

Flowchart of break:

break statement

using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace break_example
{
Class brk_stmt
{
    public static void main(String[] args)
    {
        for (int i = 0; i <= 5; i++)
        {
            if (i == 4)
            {
                break;
            }
            Console.WriteLine("The number is " + i);
            Console.ReadLine();
        }
    }
}
}

Output:
The number is 0;
The number is 1;
The number is 2;
The number is 3;

continue statement:

We can terminate an iteration without exiting the loop body using the continue keyword. When continue (jump statement) execute within the body of the loop, all the statements after the continue will be skipped and a new iteration will start. In other words, we can understand that continue causes a jump to the end of the loop body.

Flowchart of continue:

continue in c

using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace continue_example
{
Class cntnu_stmt
{
    public static void main(String[] {
        for (int i = 0; i <= 5; i++)
        {
            if (i == 4)
            {
                continue;
            }
            Console.WriteLine(“The number is "+ i);
                              Console.ReadLine();
        }
    }
}
}

Output:
The number is 1;
The number is 2;
The number is 3;
The number is 5;

 

Q) What can you tell us about the XSD file in C#?

XSD denotes XML Schema Definition. The XML file can have any attributes, elements, and tags if there is no XSD file associated with it. The XSD file gives a structure for the XML file, meaning that it determines what, and also the order of, the elements and properties that should be there in the XML file. Note: – During serialization of C# code, the classes are converted to XSD compliant format by the Xsd.exe tool.

 

Q) What are Custom Control and User Control?

Custom Controls are controls generated as compiled code (Dlls), those are easier to use and can be added to the toolbox. Developers can drag and drop controls to their web forms. Attributes can, at design time. We can easily add custom controls to Multiple Applications (If Shared Dlls). So, If they are private, then we can copy to dll to bin directory of web application and then add reference and can use them.

User Controls are very much similar to ASP include files, and are easy to create. User controls can’t be placed in the toolbox and dragged – dropped from it. They have their design and code-behind. The file extension for user controls is ascx.

 

Q) What are sealed classes in C#?

We create sealed classes when we want to restrict the class to be inherited. The sealed modifier used to prevent derivation from a class. If we forcefully specify a sealed class as the base class, then a compile-time error occurs.

 

Q) What is the difference between Array and Arraylist?

There are some differences between a ref and an out that I have arranged in a table for easier comparison:

Array ArrayList
An Array is strongly-typed. We can store only the same type of data. ArrayList is a non-generic collection type. ArrayList’s internal Array is of the object type. So, we can store multiple types of data in ArrayList.
Array stores a fixed number of elements. ArrayList is dynamic in terms of capacity. If the number of elements exceeds, ArrayList will increase to double its current size.
Array provides better performance than ArrayList. If we are using a large number of ArrayList then it degrades performance because of boxing and unboxing.
Array uses static helper class Array which belongs to system namespace ArrayList implements an IList interface so, it provides a method that we can use for easy implementation.
Array belongs to namespace System ArrayList belongs to the namespace System.Collection
The Array cannot accept null. An Array can accept null.
Example:string[] array1=new string[5];array1[0]=”Hello”;array1[1]=”Bye”;
Example:ArrayList a1=new ArryList();a1.add(null);a1.insert(1,”hi”);a1.add(3);a1.add(8.23);

 

Q) Can a private virtual method can be overridden?

No, because they are not accessible outside the class.

 

Q) What are Properties in C#?

C# properties are members of a C# class that provide a flexible mechanism to read, write or compute the values of private fields, in other words, by using properties, we can access private fields and set their values. Properties in C# are always public data members. C# properties use to get and set methods, also known as accessors, to access and assign values to private fields.

Q) What are accessors?

The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property. The set accessor specifies that we can assign a value to a private field in a property. Without the set accessor property, it is like a read-only field. With the ‘get’ accessor we can access the value of the private field. In other words, it returns a single value. A Get accessor specifies that we can access the value of a field publically.
We have three types of properties: Read/Write, ReadOnly, and write-only.

Q) What are the differences between System.String and System.Text.StringBuilder classes?

System.String is immutable. When we modify the value of a string variable, then a new memory is allocated to the new value and the previous memory allocation released. System.StringBuilder was designed to have a concept of a mutable string where a variety of operations can be performed without allocating separate memory locations for the modified string.

Q) Why Properties are introduced in C#?

Properties are introduced in C# due to the below-mentioned reasons.

  • If the members of a class are private then how another class in C# will be able to read, write, or compute the value that field.
  • If the members of the class are public then another class may misuse that member.

 

Q) What is the difference between the dispose and finalize methods in C#?

The finalize and dispose methods are used to free unmanaged resources. There are some differences between a finalize and dispose that I have mentioned below.

Finalize:

  • Finalize is used to free unmanaged resources that are not in use, like files, database connections in the application domain and more. These are resources held by an object before that object is destroyed.
  • In the Internal process, it is called by Garbage Collector and can’t be called manual by user code or any service.
  • Finalize belongs to System.Object class.
  • Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.

Dispose:

  • Dispose is also used to free unmanaged resources that are not in use like files, database connections in the Application domain at any time.
  • Dispose is explicitly called by manual user code.
  • If we need to use the dispose method, we must implement that class via IDisposable interface.
  • It belongs to IDisposable interface.
  • Implement this when you are writing a custom class that will be used by other users.

 

Q) What are partial classes?

A partial class is only used to split the definition of a class in two or more classes in the same source code file or more than one source file. You can create a class definition in multiple files, but it will be compiled as one class at run time. Also, when you create an instance of this class, you can access all the methods from all source files with the same object.

Partial Classes can be created in the same namespace. It isn’t possible to create a partial class in a different namespace. So use the “partial” keyword with all the class names that you want to bind together with the same name of a class in the same namespace.

Syntax:
public partial Clas_name  
{
        // code
}
Let’s see an example:
// C# program to illustrate the problems 
// with public and private members 
using System;

public partial class Coords
{
    private int x;
    private int y;

    public Coords(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

public partial class Coords
{
    public void PrintCoords()
    {
        Console.WriteLine("Coords: {0},{1}", x, y);
    }
}

class TestCoords
{
    static void Main()
    {
        Coords myCoords = new Coords(6, 27);
        myCoords.PrintCoords();

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Output:

Coords: 10,15
Press any key to exit.

 

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

Using Clone() method, we create a new array object containing all the elements in the original Array and using CopyTo() method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy.

 

Q) What are the advantages of partial classes?

Below we are mentioning a few advantages of the partial class.

  • With the help of the partial class, multiple developers can work simultaneously in the same class in different files.
  • With the help of a partial class concept, you can separate UI design code and business logic code so that it is easy to read and understand.
  • When you were working with automatically generated code, the code can be added to the class without having to recreate the source file like in Visual studio.
  • You can also maintain your application in an efficient manner by compressing large classes into small ones.

 

Q) What is the difference between late binding and early binding in C#?

Early Binding and Late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object-oriented programming that allows a language to use the same name in different forms. For example, a method named Add can add integers, doubles, and decimals.
Polymorphism we have 2 different types to achieve that:
  • Compile Time also known as Early Binding or Overloading.
  • Run Time is also known as Late Binding or Overriding.

Compile Time Polymorphism or Early Binding

In Compile time polymorphism or Early Binding, we will use multiple methods with the same name but different types of parameters, or maybe the number of parameters. Because of this, we can perform different-different tasks with the same method name in the same class which is also known as Method overloading. Let see an example code,

using System;

public class Addition
{
    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }
    public int Add(int a, int b)
    {
        return a + b;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Addition dataClass = new Addition();
        int add2 = dataClass.Add(45, 34, 67);
        int add1 = dataClass.Add(23, 34);
        Console.WriteLine("Add Results: {0},{1}",add1,add2);
    }
}

Output: 

Add Results: 57,146

 

Run Time Polymorphism or Late Binding

Run time polymorphism is also known as late binding. In Run Time Polymorphism or Late Binding, we can use the same method names with the same signatures, which means the same type or the same number of parameters, but not in the same class because the compiler doesn’t allow for that at compile time.

Therefore, we can use that bind at run time in the derived class when a child class or derived class object will be instantiated. That’s why we call it Late Binding.  Let see an example code,

using System;

class UnknownAnimal  // Base class (parent)
{
    public virtual void animalSound()
    {
        Console.WriteLine("Unknown Animal sound");
    }
}


class Dog : UnknownAnimal  // Derived class (child)
{
    public override void animalSound()
    {
        Console.WriteLine("The dog says: bow wow");
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create a UnknownAnimal object
        UnknownAnimal someAnimal = new UnknownAnimal();

        // Create a Dog object
        UnknownAnimal myDog = new Dog();

        someAnimal.animalSound();
        myDog.animalSound();
    }
}

Output:

Unknown Animal sound
The dog says: bow wow

 

Q) What are the differences between IEnumerable and IQueryable?

There are some differences between an IEnumerable and an IQueryable that I have arranged in a table for easier comparison:

IEnumerable

IQueryable

IEnumerable belongs to System.Collections Namespace. IQueryable belongs to System.Linq Namespace
It has no base interface It derives from IEnumerable
 does not support Lazy Loading.  Support Lazy Loading.
While querying data from the database, IEnumerable executes a select query on the server-side, load data in-memory on client-side and then filter data. Hence does more work and becomes slow. While querying data from the database, IQueryable executes select queries on the server-side with all filters. Hence does less work and becomes fast.
It suitable for LINQ to Object and LINQ to XML queries It is suitable for LINQ to SQL queries.
Doesn’t support Custom Query Supports Custom Query using CreateQuery and Execute methods
Extension methods supported in IEnumerable takes functional objects. Extension methods supported in IEnumerable takes expression objects, i.e., expression tree.
IEnumerable is used when querying data from in-memory collections like List, Array, etc. IQueryable is used When querying data from out-memory (like remote database, service) collections.
Its best use in-memory traversal Its best use in Paging.

 

Q) What is Reflection in C#?

Reflection is the process of runtime type discovery to inspect metadata, CIL code, late binding, and self-generating code. At the run time by using reflection, we can access the same “type” information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events, and properties.

You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace.

Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also used in the external disassembling tools such as Reflector, Fxcop, and NUnit because .NET tools don’t need to parse the source code similar to C++.

Metadata Investigation 

The following program depicts the process of reflection by creating a console-based application. This program will display the details of the fields, methods, properties, and interfaces for any type within the mscorlib.dll assembly. Before proceeding, it is mandatory to import “System.Reflection”.

Here, we are defining a number of static methods in the program class to enumerate fields, methods, and interfaces in the specified type. The static method takes a single “System.Type” parameter and returns void.

static void FieldInvestigation(Type t)
{
    Console.WriteLine("*********Fields*********");
    FieldInfo[] fld = t.GetFields();
    foreach(FieldInfo f in fld)
    {
        Console.WriteLine("-->{0}", f.Name);
    }
}

static void MethodInvestigation(Type t)
{
    Console.WriteLine("*********Methods*********");
    MethodInfo[] mth = t.GetMethods();
    foreach(MethodInfo m in mth)
    {
        Console.WriteLine("-->{0}", m.Name);
    }
}

 

Q) Give an example of removing an element from the queue?

The dequeue method is used to remove an element from the queue.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestApplication
{
class Program
{
    static void Main(string[] args)
    {
        Queue qt = new Queue();
        qt.Enqueue(1);
        qt.Enqueue(2);
        qt.Enqueue(3);

        foreach (Object obj in qt)
        {
            Console.WriteLine(obj);
        }
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("The number of elements in the Queue " + qt.Count);
        Console.WriteLine("Does the Queue contain " + qt.Contains(3));
        Console.ReadKey();
    }
}
}

 

Q) What is the difference between directcast and ctype?

DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in DirectCast.

Ctype is used for conversion where the conversion is defined between the expression and the type.

 

Q) How to implement a singleton design pattern in C#?

In a singleton pattern, a class can only have one instance and provides an access point to it globally.

Example,

Public sealed class Singleton
{
    Private static readonly Singleton _instance = new Singleton();
}

 

Q) What is the difference between the “throw” and “throw ex” in .NET?

“Throw” statement preserves original error stack whereas “throw ex” has the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

 

Q) List down the commonly used types of exceptions in .net?

ArgumentNullException , ArgumentOutOfRangeException, ArithmeticException, DivideByZeroException , ArgumentException, IndexOutOfRangeException ,InvalidCastException ,InvalidOperationException , IOEndOfStreamException , NullReferenceException , OutOfMemoryException , StackOverflowException,OverflowException , etc.

 

Q) How can we sort the elements of the Array in descending order?

Using Sort() methods followed by Reverse() method.

 

Q) What is a Hashtable in C#?

A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in a Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. Access to the table’s values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.

The Hashtable Collection:

The Base Class libraries offer a Hashtable Class that is defined in the System.Collections namespace, so you don’t have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is automatically increased as required through reallocation. It is an older .Net Framework type.

Declaring a Hashtable:

The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the examples, we have to add using System.Collections; to the source code. The declaration for the Hashtable is:

Hashtable HT = new Hashtable ();

 

Q) What is Multithreading with .NET?

Multithreading allows a program to run multiple threads concurrently. This article explains how multithreading works in .NET. This article covers the entire range of threading areas from thread creation, race conditions, deadlocks, monitors, mutexes, synchronization and semaphores and so on.

The real usage of a thread is not about a single sequential thread, but rather using multiple threads in a single program. Multiple threads running at the same time and performing various tasks are referred to as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of the resources allocated for that program.

A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.

 

I hope above mentioned C# Interview Questions was helpful for you. If you want to add any other important C# Interview Questions, please write in the comment box or directly send an email. I will add your C# Interview Questions.

Recommended Post:

 

References: