All Interviews

07/Jul/2020 | 10 minutes to read

Best Answers to C# Interview Questions

QFLES is listing some Essential C# Interview Questions and Answers for Freshers and mid level of Experienced Professionals prepared by Industry Experts. All answers for these C# interview questions are given based on standard documents and tried to explain in simple and easiest way.


1. What is latest version of C# with features?

C# 1.0 released in 2002. Like other languages Microsoft is also releasing it's new versions every year. Latest Version of C# is 8.0. For more you can visit Microsoft official site Releases . There are many new features in C# 8.0. You can go through Here.

2. Differentiate const vs readonly vs static

Constant

Constant fields are defined at the time of declaration in the code snippet, because once they are defined they can't be modified. By default a constant is static, so you can't define them static from your side. It is also mandatory to assign a value to them at the time of declaration otherwise it will give an error during compilation of the program snippet. That's why it is also called a compile-time constant. Fore more follow const .

ReadOnly

A Readonly field can be initialized either at the time of declaration or within the constructor of the same class. We can also change the value of a Readonly at runtime or assign a value to it at runtime (but in a non-static constructor only). For that reason a Readonly field is also called a run-time constant. For more follow readonly .

Static

A static member (variable, method, etc) belongs to the type of an object rather than to an instance of that type. For more follow static .

3. Differentiate in vs ref vs out

In

It is like ref or out keywords but 'in' arguments can not be modified by called method. 'in' arguments must be initialized before passing to called method. If you will try to modify the value of 'in' argument in calling method it will throw error. So it's like a readonly variable. For more in .

Ref

The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the called method is reflected in the calling method. ref argument may be modified by called method. For more ref .

Out

The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword. out arguments must be modified by called method. For more out .

4. What is Inheritance? Why C# does not support multiple Inheritance?

To understand this you need to understand the Diamond problem first: diamond problem
The Diamond problem (sometimes referred to as the "deadly diamond of death") is an ambiguity that arises when two classes B and C inherit from Class A and class D inherits from both B and C. If a method in D calls a method defined in A(and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B or C?

5. What is Shadowing or Hiding?

Shadowing

In C# it's known as method Hiding. Shadowing is VB.Net concept. It hides the base class method implementation. It can achieved using 'new' keyword. If a method is not overriding the derived method that means it's hiding it.
Override keyword is used to provide a completely new implementation of a base class method or extend base class method (which is marked 'Virtual') in the derived class. While New keyword just hides the base class method not extend it.
If the derived class thinks that, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition.
class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output : DC:Display
On compilation the above program will throw a warning which said test.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member 'BC.Display()'. Use the new keyword if hiding was intended. test.cs(3,15): (Location of symbol related to previous warning) So modify the code as below.
class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

6. What is the difference between Var, Object and Dynamic keywords?

I am giving one example from this you will understand the differences.

class Program
    {
        static void Main(string[] args)
        {
            var x = 10;
            object y = 20;
            dynamic z = 30;

            x = "bhanu"; // Error -  Cannot implicitly convert type 'string' to 'int'

            y = "bhanu";
            y = y - 10;  //Error Operator '-' cannot be applied to operands of type 'object' and 'int'

                   z = "bhanu";
            z = z - 10;
            Console.WriteLine("{0},{1},{2}",x,y,z);
            Console.ReadLine();
        }

        void disp(var x) // Error CS0825  The contextual keyword 'var' may only appear within a local variable declaration or in script code
        {

        }
        void disp(object x)
        {

        }
        void disp1(dynamic x)
        {

        }
    }

var

Var was introduced with C# 3.0, It can store any type of value but It is mandatory to initialize var types at the time of declaration.
It is type safe i.e. Compiler has all information about the stored value, so that it doesn't cause any issue at run-time.
Var type cannot be passed as method argument and method cannot return object type. Var type work in the scope where it defined.refer example
No need to cast because compiler has all information to perform operations. And doesn't cause problem because compiler has all information about stored value.
Useful when we don’t know actual type i.e. type is anonymous. refer example.
For more var type .

object

Object was introduced with C# 1.0, It can store any kind of value, because object is the base class of all type in .NET framework.
Compiler has little information about the type.
Object type can be passed as method argument and method also can return object type. as in above example.
Need to cast object variable to original type to use it and performing desired operations. And cause the problem at run time if the stored value is not getting converted to underlying data type.
Useful when we don’t have more information about the data type. refer example.
For more object type .

dynamic

Dynamic was introduced with C# 4.0, It can store any type of the variable, similar to old VB language variable.
It is not type safe i.e. Compiler doesn't have any information about the type of variable.
Dynamic type can be passed as method argument and method also can return dynamic type. Refer example.
Casting is not required but you need to know the properties and methods related to stored type. And cause problem if the wrong properties or methods are accessed because all the information about stored value is get resolve only at run time.
Useful when we need to code using reflection or dynamic languages or with the COM objects, because you need to write less code.
For more dynamic .

7. Can Virtual or Abstract member be declare private ?

No, It will throw compile time error.

virtual void display() // will throw error here
        {
        // Implementation

        }

8. What is Boxing and Unboxing in C# ?

Boxing

In boxing A value type is converted to the type 'object' or to any interface type implemented by this value type. When CLR boxes a value type it wraps the value inside a System.Object instance and stored in managed heap.

UnBoxing

When a value type is extracted from the 'Object' is called unboxing. Boxing is implicit and unboxing is explicit.
Boxing and Unboxing example:
int a = 13;
            // The below line boxes i.
            object o = i; 
The object o can then be unboxed and assigned to integer variable i:
o = 13;
            a = (int)o;  // unboxing
For more Boxing and Unboxing in C# .

9. What is Method Overloading?

When you define a method with same name but different method signature in a class is called method overloading. Method Signature does not include method return type.
For method overloading you can use different types of parameters or different sequence of parameters or different number of parameters.
Method overloading example:

        void display(int x)
        {
        // Implementation
        }
        void display(float x)
        {
            // Implementation
        }
        void display(int x, int y)
        {
            // Implementation

        }
In this example method name is same 'display' in all three cases but method signature is different.

10. What are Value Type and Reference Type?

Value Types

Variables of value types directly contains their data that means if A data type is value type then it holds the data within it's memory allocation. With value types, each variable has its own copy of the data, and it is not possible for operations on one variable to affect the other (except in case of the by Ref modifier). Value types include the following:
  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong
For more Value Types in C# .

Reference types

Variables of reference types stores references (memory address) to their data, two variables can reference the same object; Or we can say that A reference type contains a pointer to another memory location that holds the data. So operations on one variable can affect the object referenced by the other variable.
The following keywords are used to declare reference types: class, interface, delegate
C# also provides the following built-in reference types: dynamic, object, string
For more Reference Types in C# .
Value Types and Reference Types in C# .

11. What is Abstraction and Encapsulation? How these are different from each other?

Abstraction and Encapsulation both are the OOPs concept. Let's look into these.

Abstraction

Abstraction is the process of removing unnecessary information of an object and keep only the required characteristics. Example: A Mobile has many things like RAM, Signals, Wi-Fi etc, but you do not need to know all these things to operate the mobile, just you need to know how can I do it switch on or off.

Encapsulation

Encapsulation is the process of putting related data and functions into a single unit (called class). Encapsulation is needed to protect the code from accidental errors. Example: A Mobile is operated just by pressing keys, all the related data and functions code is written in some unit, just you need to call some function like press the key, it will start to operate.

Main difference between encapsulation and abstraction:

These are the below differences between abstraction and encapsulation.
  • Abstraction is achieved at design level but Encapsulation is achieved at Implementation level.
  • Abstraction is about to show only relevant information, Encapsulation is about putting related things into a single unit.

12. What is the deference between Interface and Abstract class? What is the need of these?

Abstract class and Interface both are used to implement a abstraction layer.

Abstract

It enables you to create classes and class members that are incomplete and must be implemented in a derived class. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

Interface

An interface defines only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. Interface is contract for clients.

Differences and why each is required?

  • Interface is required to implement multiple inheritance concept in c# as Abstract class does not support it.
  • Interface does not contain data members and constructors but Abstract class contains data members and constructors.
  • Interface contains only incomplete members but Abstract class contains both incomplete(abstract) and complete members.
  • Members of Interface can not be static but complete members of Abstract class can be static.

Need of Interface

As C# does not support multiple inheritance concept so we can achieve that using multiple interfaces. Many design patterns are based on Interface rather than class inheritance, Dependencies are injected using interfaces as Unit testing will be easy by providing different implementations.

13. What is Polymorphism? Describe the static and Dynamic Polymorphism?

14. What will be output of below program? 'Error Line' will throw any error?

  class A
    {
       public virtual void display()
        { Console.WriteLine("A - display"); }
    }
    class B:A
    {
        public override void display()
        { Console.WriteLine("B - display"); }
    }
    class Test
    {
        static void Main()
        {
            A obj = new A();
            obj.display();

            A obj1 = new B();
            obj1.display();

            B o = new B();
            o.display();
            // B ob = new A();  Error Line
            Console.ReadLine();
        }
    }

Output: 'Error Line' will throw error - Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists (are you missing a cast?).
Output will be as below.
A - display
B - display
B - display

16. Can Abstract class has constructor? Below code will compile or not, or it will give any error in Error line 1 or 2.

class A
    {
       public virtual void display()
        {
            Console.WriteLine("A - display");
        }
        public virtual void disp()
        {
            Console.WriteLine("A - disp");
        }
    }
abstract class ab :A
    {
        public ab()
        { }
        public abstract override void display(); Error Line 1

        public sealed override void disp()  Error Line 2
        {
            Console.WriteLine("disp is sealed now.");
        }
    }

Solution: Abstract class can contain the constructor. Constructor is used to instantiate the class instance members.
Above code will compile successfully. We can add Abstract and Sealed keywords with the override keyword.

17.

18.

Some General Interview Questions for C#:

1. How much will you rate your self in C#?

When you attend an interview, Interviewer may ask you to rate your self in specific Technology like C#, So It's depend on your knowledge and work experience in C#.

2. What challenges did you face while working on C#?

This question may be specific to your technology and completely depends on your past work experience. So you need to just explain the challenges you faced related to C# in your Project.

3. What was your role in last Project related to C#?

It's based on your role and responsibilities assigned to you and what functionality you implemented using C# in your project. This question is generally asked in every interview.

4. How much experience do you have in C#?

Here you can tell about your overall work experience on C#.

5. Have you done any C# Certification or Training?

It's depend on candidate like you have done any C# training or certification. Certifications or trainings are not essential but good to have.

Conclusion:

We have covered some frequently asked C# Interview Questions and Answers to help you for your Interview. All these Essential C# Interview Questions are targeted for mid level of experienced Professionals and freshers.
While attending any C# Interview if you face any difficulty to answer any question please write to us at [email protected]. Our IT Expert team will find the best answer and will update on portal. In case if we find any new C# questions, we will update the same here.