C# Interview Question and Answers with Example - Part 1

Below is top C# interview question and answers with examples for freshers and intermediate developers.

Views: 540

What is C#?

C# is a general-purpose, object-oriented programming language developed by Microsoft around 2000. It is strongly type and it encompasses imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines.

What is current version of C#?

Current version of C# is C# 7.3 (as of this writing(Aug 30, 2018)). Below are the version history of C#.

C# 1.0January 2002
C# 1.1April 2003
C# 1.2April 2003
C# 2.0November 2005
C# 3.0November 2007
C# 4.0April 2010
C# 5.0August 2012
C# 6.0July 2015
C# 7.0March 2017
C# 7.1August 2017
C# 7.2November 2017
C# 7.3May 2018

What are the new features added in C#?

Below are the new features added with C# versions.

C# 7.3
  • Accessing fixed fields without pinning
  • Reassigning ref local variables
  • Using initializers on stackalloc arrays
  • Using fixed statements with any type that supports a pattern
  • Using additional generic constraints
C# 7.2
  • Reference semantics with value types
  • Non-trailing named arguments
  • Leading underscores in numeric literals
  • private protected access modifier
C# 7.1
  • Async main
  • Default literal expressions
  • Inferred tuple element name
C# 7.0
  • Out variables
  • Pattern matching
  • Deconstruction
  • Local functions
  • Digit separators
  • Binary literals
  • Ref returns and locals
  • Generalized async return types
  • Expression bodied constructors and finalizers
  • Expression bodied getters and setters
  • Throw can also be used as expression
C# 6.0
  • Compiler-as-a-service
  • Import of static type members into namespace
  • Exception filters
  • Await in catch/finally blocks
  • Auto property initializers
  • Default values for getter-only properties
  • Expression-bodied members
  • Null propagator (null-conditional operator, succinct null checking)
  • String interpolation
  • nameof operator
  • Dictionary initializer
C# 5.0
  • Asynchronous methods
  • Caller info attributes
C# 4.0
  • Dynamic binding
  • Named and optional arguments
  • Generic co- and contravariance
  • Embedded interop types
C# 3.0
  • Implicitly typed local variables
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expression
  • Expression trees
  • Partial
C# 2.0
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Getter/setter separate accessibility
  • Method group conversions (delegates)
  • Co- and Contra-variance for delegates
  • Static classes
  • Delegate inference

What are the OOPS concepts?

Below is the main oops concepts of C#.

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polyporphism

What is Inheritance?

Inheritance is when an object or class is based on another object or class, using the same implementation or specifying implementation to maintain the same behaviour.

What is Encapsulation?

Encapsulation is a packing of data and functions into a single component. It prevents access to implementation details. Class is an example of encapsulation

What is Abstraction?

Abstraction refers to represent essential data without including the background details. Abstractions can be achieved by means of access specifiers

What is Polyporphism?

Polymorphism means one object behaving as multiple forms. There is compile time and runtime polyporphism. In compile time polymorphism, we can declare methods with same name but different parameters and it is called as method overloading.
Runtime polymorphism can be achieved by method overriding.

What is Class in C#?

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type.

What is Object in C#?

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

What is Value Type and Reference Type?

Value Type A value type variable holds data value within own memory space that means this variable contains their value directly. Data of value type stored in Stack memory. Below data types are value type.

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort
Reference Type A reference type variable contains a pointer to another memory location that holds the actual data. Reference is stored in stack memory and actual data is stored in heap memory. A reference variable stores address of actual object whereas actual object is stored in heap memory. Below data types are Reference type.
  • class
  • interface
  • delegate
  • array

What are the differences between value types and reference types?

1. Value types are stored on the stack where as reference types are stored on the managed heap.
2. Value type variables directly contain their values where as reference variables holds only a reference to the location of the object that is created on the managed heap.
3. There is no heap allocation or garbage collection overhead for value-type variables. As reference types are stored on the managed heap, they have the over head of object allocation and garbage collection.
4. Value Types cannot inherit from another class or struct. Value types can only inherit from interfaces. Reference types can inherit from another class or interface.

Explain the passing parameters by value and passing parameters by reference with an example

Passing by Value When you pass a value type variable from one method to another method, the system creates a separate copy of a variable in another method, so that if value got changed in the one method won't affect on the variable in another method.

namespace ConsoleApplication1
    class Program
        public static void Main()
            int A = 10;
            Console.WriteLine("Value of A before passing to method = " + A);
            Console.WriteLine("Value of A after passing to method = " + A);
        public static int MyFunction(int number)
            int changedValue = number + 5;
            return changedValue;
Value of A before passing to method = 10
Value of A after passing to method = 10

Passing by Reference When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the address of the variable. If we change the value of the variable in a method, it will also be reflected in the calling method.

namespace ConsoleApplication1
    class Program
        public static void Main()
            MyClassofReferenceType obj = new MyClassofReferenceType();
            obj.A = 10;
            Console.WriteLine("Value of A before passing to method = " + obj.A);
            MyFunction(obj); //passing same object
            Console.WriteLine("Value of A before passing to method = " + obj.A); // here same object is modified
        public static void MyFunction(MyClassofReferenceType MyClassofReferenceTypeObj)
            MyClassofReferenceTypeObj.A = MyClassofReferenceTypeObj.A + 5;
    class MyClassofReferenceType
        public int A;
Value of A before passing to method = 10
Value of A after passing to method = 15

What is namespace in C#?

A namespace is used to organize your code logically. A namespace in collection of classes, interface, structs, enums, delegates and other namespaces.

What is difference between ref and out parameter or ref and out keywords?

The ref and out keywords are used to pass the parameter to the function. Both Ref and out keywords are used to pass parameter by reference. ref: The ref keyword is used to pass parameter as reference. If value of parameter is changed in called method then parameters changed value is also gets reflected in calling method. The parameter must be initialized in calling method before it passed to called method. out: The out keyword is also used to pass parameter as reference. Here, initialization of parameter is not necessary in calling method before passing parameter to called method. But, initialization is compulsory in called method before returning back to called method. Ex.

namespace ConsoleApplication1
    class Program
        static void Main(string[] args) // calling method
            int number1 = 10;      // must be initialized before passing to Method1 
            int number2;           // it can be optional or can be initialized

            Method1(ref number1);

            Method2(out number2);


        static void Method1(ref int number1) // called method
            number1 = 11;
        static void Method2(out int number2) // called method
            number2 = 12;  // must be initialized


Note: 1) A data type of value type or reference type can be pass to method by ref keyword. But, if a value type is passed using ref keyword then boxing does not occurs.
2) Properties cannot be passed using ref or out keyword as they are implemented as function internally.

What is boxing and unboxing?

The process of converting value type to reference type is boxing and reference type to value type in unboxing. Boxing and unboxing is not a data type conversion. Boxing is basically storing a value type as an object in heap and unboxing is reading the value from the object. Ex.

namespace ConsoleApplication1
    class Program
        static void Main(string[] args) // calling method
            int a = 10;
            object obj = (object)a; // Boxing
            int b = (int)obj;   // unboxing

Is boxing an implicit conversion?

Yes, boxing happens implicitly.

Is unboxing an implicit conversion?

No, unboxing is an explicit conversion.

What happens during the process of boxing?

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.

What do you mean by casting a data type?

Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.

What are the 2 kinds of data type conversions in C#?

Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes. Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.

What is the difference between an implicit conversion and an explicit conversion?

Explicit conversions require a cast operator where as an implicit converstion is done automatically.
Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.

Will the following code compile?

double d = 9999.11;
int i = d;
No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.
double d = 9999.11;
int i = (int)d; //Cast double to int.

If you want to convert a base type to a derived type, what type of conversion do you use?

Explicit conversion as shown below. Consider Vehicle as base class and Car as derived class.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;
// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;

What operators can be used to cast from one reference type to another without the risk of throwing an exception?

The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

Views: 540