Here is the next best gift for C# developers: a list of commonly asked C# interview questions. Here are the top C# interview questions and their answers prepared by C# experts. These C# developer interview questions cover various topics like the difference between ref and out parameters, enum, boxing and unboxing, Asynchronous Methods etc. Get prepared with these C# basic interview questions and live your dream career as a C# developer.
C# is pronounced as "See Sharp".
C# is a type-safe object-oriented programming language developed by Microsoft which runs under the .NET framework.
C# enables the developers to build a variety of secure and robust applications like windows client applications, client-server application, XML web services, distributed components, database applications etc.
The argument passed as ref must be initialized before passing to the method. It means when the value of this parameter is changed in the method, it will get reflected in the calling method.
The argument passed as out parameter need not be initialized before passing to the method.
public class RefAndOut { public static void Main() { int val1 = 0; //must be initialized int val2; CallwithRef (ref val1); Console.WriteLine(val1); CallWithOut (out val2); Console.WriteLine(val2); } static void CallwithRef(ref int value) { value = 1; } static void CallWithOut(out int value) { value = 2; //must be initialized } }
Output
1 2
An enumeration is a list of named integer constants called enumerator list. An enumerated type is declared using the “enum” keyword.
C# enumeration is value data type and enumeration contains its own values and cannot inherit.
By default, enum has internal access but can also be declared as public.
By default, the first enumerator has the value 0 and the value of each successive enumerator is increased by 1. Example: enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };
In enum, Days Sat is 0, Sun is 1, Mon is 2, and so on. You can also change the default values for enumerators. Also, we can change the default value of the enumerator.
Use of enum is to define the static constants.
Boxing is a process of converting a value type to reference type. This is an implicit conversion. We can directly assign a value to an object and C# will manage that conversion.
Example : int i = 10; object obj = i; // Box the integer type i into object type obj.
The reverse process of Boxing is an unboxing. Unboxing is a procedure of converting reference type to value type. This has to be done explicitly. The object type is explicitly cast to the value type.
Example : int i = 10; object obj = i; // Box the integer type i into object type obj. int j = (int) obj; // Unbox the integer value stored in object type obj to integer type j.
Object class is the ultimate base class of all the classes in the .NET Framework. It is the root of the type hierarchy.
The ?? operator is called the null-coalescing operator. This operator is used to define a default value for a nullable value type or reference type variable If an operand is not null then it returns left-hand operand, otherwise it returns the right-hand operand.rand.
Example :
class nullablecheck { static void Main(string[] args) { string i = null; string j = i ?? “Default Value””; Console.WriteLine(j); Console.ReadLine(); } }
Output :
Default Value
A ternary operator takes three arguments.
The first argument is a comparison argument, the second argument is value if the result of the comparison is true. And the third argument is value if the result of the comparison is false.
This operator is used to reduce the lines in the code and increase the readability.
Example:
int i = 10; string message; message = I < 0 ? “Negative” : “Positive”
Here is a list of things associated with String and StringBuilder Classes.
C# supports five types of access modifiers as given below-
In C#, Codes are differentiated between safe and unsafe code. A code which is runs under the CLR is called the safe code.
The unsafe code does not run under the management of CRL. Other words, unsafe codes are not garbage collected. Thus, it is important that all unsafe codes are managed separately and carefully.
Using unsafe keyword of C#, we can mark the entire method or code block or individual statement as unsafe.
Example: public unsafe void MyUnsafeMethod() {
// write unsafe code here }
Here are some of the important things to note :
Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for using the namespace in other namespaces.
"Convert.toString" function handles NULLS, while ".ToString()" does not handle the null value and throws an exception.
Example : string s; object o = null; s = o.ToString(); //returns a null reference exception for s.
string s; object o = null; s = Convert.ToString(o); //returns an empty string for s and does not throw an exception.
When we want to define a function with ‘n’ arguments, we can use the params keyword in front of the definition of the last parameter.
These n number of arguments are changed by the compiler into elements in a temporary array and actually, this array is received at the receiving end.
public class ParamsExample { static decimal TotalSum(decimal d1, params int[] values) { decimal total = d1; foreach (int value in values) { total += value; } return total; } static void Main() { decimal d1 = 100; int sum1 = TotalSum(d1, 1); Console.WriteLine(sum1); int sum2 = TotalSum(sum1, 1, 2); Console.WriteLine(sum2); Console.Read(); } } /* Output 101 104 */
A jagged array is called an "array of arrays."
A jagged array is a special type of array whose elements are arrays of different dimensions and sizes.
Jagged array’s elements must be initialized before its use.
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[3]; //contains 3 elements jaggedArray[1] = new int[2]; //contains 2 elements jaggedArray[2] = new int[4]; //contains 4 elements
In the jagged array, it is necessary to specify the value in the first bracket [] since it specifies the jagged array size.
In C#, a structure is a value type which contains data members and members function like class. The structure can contain fields, methods, constants, constructors, properties, indexers, operators and other nested structure types.
Like a class, a struct can have methods, fields, indexers, properties, operator methods, events and nested structure.
Structures are useful for small data structures and provide better performance as compared to class.
When we are dealing with resources in a program, we should use the using keyword. When we use the using keyword for any of the file operations or a database connection etc, the statement obtains the resource, uses it and calls dispose method after use and cleans up the specified resource when the execution is completed.
Example:
using (SqlConnection con = new SqlConnection(connectionString)) { // perform sql statements etc.. }
When we have to implement a singleton class pattern, we can declare a constructor private.
Private constructor contains only static members. As it is private constructor, it cannot be externally called. If a class that has one or more private constructor and no public constructor, then other classes except nested classes are not allowed to create an instance of this class and it cannot be inherited.
Sealed classes are special types of class that is being restricted to be inherited. The sealed modifier is used to prevent a class inheritance. If you try to inherit a sealed class then a compile-time error occurs.
Example: Sealed class Example
{ void Display() { Console.WriteLine("Sealed class method!"); } } class MyExample : Example { void Show() { Console.WriteLine("Show method!"); } } Produces error , 'MyExample' cannot derive from sealed type 'Example'
In C#, a structure is a value type which contains data members and members function like class. The structure can contain fields, methods, constants, constructors, properties, indexers, operators and other nested structure types.
Like a class, a struct can have methods, fields, indexers, properties, operator methods, events and nested structure.
Structures are useful for small data structures and provide better performance as compared to class.
From C# 5.0, keywords async and await are introduced.
Before C# 5.0, for writing asynchronous code, We needed to write callbacks.
As shown in the example, we can use these keywords in combination. We have added await operator to an async operation. When the method returns the Task Response / Result again the execution happens normally
Example: public async Task<IEnumerable<Price>> GetPriceList() { HttpClient client = new HttpClient();
Uri address = new Uri("https://amazon.in/"); client.BaseAddress = address; HttpResponseMessage response = await client.GetAsync("api/product/5/price/");
if (response.IsSuccessStatusCode) { var list = await response.Content.ReadAsAsync<IEnumerable<Price>>(); return list; } else { return null; } }
Encapsulation is an object-oriented design principle that reduces coupling between objects and encourages maintainable code.
Encapsulation in C# is implemented with different levels of access to object through the access specifiers—public, private, protected, internal, and protected internal.
There are three types of casting which are supported in C#.
Implicit conversion: The compiler itself takes care of this and it guarantees no loss of data. In this type of type conversion smaller data type to larger data type conversion, and conversion of derived classes to base class with safety.
Explicit conversion: Done by using the cast operator. It includes conversion of the larger data type to smaller data type and conversion of the base class to derived classes. In this conversion information might be lost or conversion might not be succeeding for some reasons. This is an unsafe type of conversion.
For example Derived d = (Derived)b;
User-defined conversion: User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to a struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static.
We can index the instance of a class or struct similiar to an array by using indexer. Unlike, property this keyword is used to define an indexer. Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. Indexer modifier can be private, public, protected or internal.
Example:
class childclass { static void Main(string[] args) { ParentClass indexes = new ParentClass(); indexes[0] = "0"; indexes[1] = "1"; for (int i = 0; i < ParentClass.size; i++) { Console.WriteLine(names[i]); } Console.ReadKey(); } } class ParentClass { private string[] range = new string[2]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; } } }
Output :
0 , 1
Delegate is a reference type which holds a reference to a class method. Any method which has the same signature as a delegate can be assigned to delegate. It is similar to function pointer but it is type safe.
Delegate is declared by the keyword delegate. To create the delegate instance we need to assign a method to delegate which has the same signature as a delegate. And then invoking a delegate same as invoking a method.
Example:
//1. Declaration
public delegate int MyDelegate(int a, int b); //delegates having the same signature as a method
public class DelegateExample {
// methods to be assigned and called by the delegate
public int Sum(int a, int b) {
return a + b; } public int Difference(int a, int b) {
return a - b; } } class Program {
static void Main() { DelegateExample obj = new DelegateExample();
// 2. Instantiation : As a single cast delegate MyDelegate sum = new MyDelegate(obj.Sum);
MyDelegate diff = new MyDelegate(obj.Difference); // 3.Invocation Console.WriteLine("Sum of two integer is = " + sum(10, 20)); Console.WriteLine("Difference of two integer is = " + diff(20, 10)); } }
There are two types of delegates: Single cast delegate: Single cast delegate holds the reference of only one method. Multi-cast delegate: A delegate which holds the reference of multiple methods is called multi-cast delegate. A multicast delegate holds the reference of the methods which return type is void.
The differences between events and delegates are given below:
The event comes with its pair of assessors i.e. Add and Remove. Which is assigned and unassigned with a += and -= operator
The event has a restrictive signature and must always be of the form Event(object sender, EventArgs args)
Defined by name - Can be static as well - Access through the name - Supports shortened syntax - A get accessor has no parameters - A set accessor has an implicit value parameter
it is identified by signature - it must be an instance member - Access through index - Doesn’t support shortened syntax - A get accessor has same parameters as it has - A set parameter has the same parameters as it has plus the value param
Destructors are techniques to remove instances of classes as soon as class close. The destructor is used to release unmanaged resources allocated by the object. It is called automatically before an object is destroyed. It cannot be called explicitly. A class can have only one destructor.
The destructor is a special type member function which has the same name as its class name preceded by a tilde (~) sign.
Example:
class DestructorExample { public DestructorExample() { Console.WriteLine("Constructor called"); } //destructor ~DestructorExample() { Console.WriteLine("Destructor called"); } } class Program { static void Main() { DestructorExample T = new DestructorExample(); GC.Collect(); } } Out Put : Constructor called Destructor called
IEnumerable: -
IQueryable: -
Finalize():
Dispose():
C# is pronounced as "See Sharp".
C# is a type-safe object-oriented programming language developed by Microsoft which runs under the .NET framework.
C# enables the developers to build a variety of secure and robust applications like windows client applications, client-server application, XML web services, distributed components, database applications etc.
The argument passed as ref must be initialized before passing to the method. It means when the value of this parameter is changed in the method, it will get reflected in the calling method.
The argument passed as out parameter need not be initialized before passing to the method.
public class RefAndOut { public static void Main() { int val1 = 0; //must be initialized int val2; CallwithRef (ref val1); Console.WriteLine(val1); CallWithOut (out val2); Console.WriteLine(val2); } static void CallwithRef(ref int value) { value = 1; } static void CallWithOut(out int value) { value = 2; //must be initialized } }
Output
1 2
An enumeration is a list of named integer constants called enumerator list. An enumerated type is declared using the “enum” keyword.
C# enumeration is value data type and enumeration contains its own values and cannot inherit.
By default, enum has internal access but can also be declared as public.
By default, the first enumerator has the value 0 and the value of each successive enumerator is increased by 1. Example: enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };
In enum, Days Sat is 0, Sun is 1, Mon is 2, and so on. You can also change the default values for enumerators. Also, we can change the default value of the enumerator.
Use of enum is to define the static constants.
Boxing is a process of converting a value type to reference type. This is an implicit conversion. We can directly assign a value to an object and C# will manage that conversion.
Example : int i = 10; object obj = i; // Box the integer type i into object type obj.
The reverse process of Boxing is an unboxing. Unboxing is a procedure of converting reference type to value type. This has to be done explicitly. The object type is explicitly cast to the value type.
Example : int i = 10; object obj = i; // Box the integer type i into object type obj. int j = (int) obj; // Unbox the integer value stored in object type obj to integer type j.
Object class is the ultimate base class of all the classes in the .NET Framework. It is the root of the type hierarchy.
The ?? operator is called the null-coalescing operator. This operator is used to define a default value for a nullable value type or reference type variable If an operand is not null then it returns left-hand operand, otherwise it returns the right-hand operand.rand.
Example :
class nullablecheck { static void Main(string[] args) { string i = null; string j = i ?? “Default Value””; Console.WriteLine(j); Console.ReadLine(); } }
Output :
Default Value
A ternary operator takes three arguments.
The first argument is a comparison argument, the second argument is value if the result of the comparison is true. And the third argument is value if the result of the comparison is false.
This operator is used to reduce the lines in the code and increase the readability.
Example:
int i = 10; string message; message = I < 0 ? “Negative” : “Positive”
Here is a list of things associated with String and StringBuilder Classes.
C# supports five types of access modifiers as given below-
In C#, Codes are differentiated between safe and unsafe code. A code which is runs under the CLR is called the safe code.
The unsafe code does not run under the management of CRL. Other words, unsafe codes are not garbage collected. Thus, it is important that all unsafe codes are managed separately and carefully.
Using unsafe keyword of C#, we can mark the entire method or code block or individual statement as unsafe.
Example: public unsafe void MyUnsafeMethod() {
// write unsafe code here }
Here are some of the important things to note :
Namespaces are containers for the classes. We will use namespaces for grouping the related classes in C#. “Using” keyword can be used for using the namespace in other namespaces.
"Convert.toString" function handles NULLS, while ".ToString()" does not handle the null value and throws an exception.
Example : string s; object o = null; s = o.ToString(); //returns a null reference exception for s.
string s; object o = null; s = Convert.ToString(o); //returns an empty string for s and does not throw an exception.
When we want to define a function with ‘n’ arguments, we can use the params keyword in front of the definition of the last parameter.
These n number of arguments are changed by the compiler into elements in a temporary array and actually, this array is received at the receiving end.
public class ParamsExample { static decimal TotalSum(decimal d1, params int[] values) { decimal total = d1; foreach (int value in values) { total += value; } return total; } static void Main() { decimal d1 = 100; int sum1 = TotalSum(d1, 1); Console.WriteLine(sum1); int sum2 = TotalSum(sum1, 1, 2); Console.WriteLine(sum2); Console.Read(); } } /* Output 101 104 */
A jagged array is called an "array of arrays."
A jagged array is a special type of array whose elements are arrays of different dimensions and sizes.
Jagged array’s elements must be initialized before its use.
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[3]; //contains 3 elements jaggedArray[1] = new int[2]; //contains 2 elements jaggedArray[2] = new int[4]; //contains 4 elements
In the jagged array, it is necessary to specify the value in the first bracket [] since it specifies the jagged array size.
In C#, a structure is a value type which contains data members and members function like class. The structure can contain fields, methods, constants, constructors, properties, indexers, operators and other nested structure types.
Like a class, a struct can have methods, fields, indexers, properties, operator methods, events and nested structure.
Structures are useful for small data structures and provide better performance as compared to class.
When we are dealing with resources in a program, we should use the using keyword. When we use the using keyword for any of the file operations or a database connection etc, the statement obtains the resource, uses it and calls dispose method after use and cleans up the specified resource when the execution is completed.
Example:
using (SqlConnection con = new SqlConnection(connectionString)) { // perform sql statements etc.. }
When we have to implement a singleton class pattern, we can declare a constructor private.
Private constructor contains only static members. As it is private constructor, it cannot be externally called. If a class that has one or more private constructor and no public constructor, then other classes except nested classes are not allowed to create an instance of this class and it cannot be inherited.
Sealed classes are special types of class that is being restricted to be inherited. The sealed modifier is used to prevent a class inheritance. If you try to inherit a sealed class then a compile-time error occurs.
Example: Sealed class Example
{ void Display() { Console.WriteLine("Sealed class method!"); } } class MyExample : Example { void Show() { Console.WriteLine("Show method!"); } } Produces error , 'MyExample' cannot derive from sealed type 'Example'
In C#, a structure is a value type which contains data members and members function like class. The structure can contain fields, methods, constants, constructors, properties, indexers, operators and other nested structure types.
Like a class, a struct can have methods, fields, indexers, properties, operator methods, events and nested structure.
Structures are useful for small data structures and provide better performance as compared to class.
From C# 5.0, keywords async and await are introduced.
Before C# 5.0, for writing asynchronous code, We needed to write callbacks.
As shown in the example, we can use these keywords in combination. We have added await operator to an async operation. When the method returns the Task Response / Result again the execution happens normally
Example: public async Task<IEnumerable<Price>> GetPriceList() { HttpClient client = new HttpClient();
Uri address = new Uri("https://amazon.in/"); client.BaseAddress = address; HttpResponseMessage response = await client.GetAsync("api/product/5/price/");
if (response.IsSuccessStatusCode) { var list = await response.Content.ReadAsAsync<IEnumerable<Price>>(); return list; } else { return null; } }
Encapsulation is an object-oriented design principle that reduces coupling between objects and encourages maintainable code.
Encapsulation in C# is implemented with different levels of access to object through the access specifiers—public, private, protected, internal, and protected internal.
There are three types of casting which are supported in C#.
Implicit conversion: The compiler itself takes care of this and it guarantees no loss of data. In this type of type conversion smaller data type to larger data type conversion, and conversion of derived classes to base class with safety.
Explicit conversion: Done by using the cast operator. It includes conversion of the larger data type to smaller data type and conversion of the base class to derived classes. In this conversion information might be lost or conversion might not be succeeding for some reasons. This is an unsafe type of conversion.
For example Derived d = (Derived)b;
User-defined conversion: User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to a struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static.
We can index the instance of a class or struct similiar to an array by using indexer. Unlike, property this keyword is used to define an indexer. Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. Indexer modifier can be private, public, protected or internal.
Example:
class childclass { static void Main(string[] args) { ParentClass indexes = new ParentClass(); indexes[0] = "0"; indexes[1] = "1"; for (int i = 0; i < ParentClass.size; i++) { Console.WriteLine(names[i]); } Console.ReadKey(); } } class ParentClass { private string[] range = new string[2]; public string this[int indexrange] { get { return range[indexrange]; } set { range[indexrange] = value; } } }
Output :
0 , 1
Delegate is a reference type which holds a reference to a class method. Any method which has the same signature as a delegate can be assigned to delegate. It is similar to function pointer but it is type safe.
Delegate is declared by the keyword delegate. To create the delegate instance we need to assign a method to delegate which has the same signature as a delegate. And then invoking a delegate same as invoking a method.
Example:
//1. Declaration
public delegate int MyDelegate(int a, int b); //delegates having the same signature as a method
public class DelegateExample {
// methods to be assigned and called by the delegate
public int Sum(int a, int b) {
return a + b; } public int Difference(int a, int b) {
return a - b; } } class Program {
static void Main() { DelegateExample obj = new DelegateExample();
// 2. Instantiation : As a single cast delegate MyDelegate sum = new MyDelegate(obj.Sum);
MyDelegate diff = new MyDelegate(obj.Difference); // 3.Invocation Console.WriteLine("Sum of two integer is = " + sum(10, 20)); Console.WriteLine("Difference of two integer is = " + diff(20, 10)); } }
There are two types of delegates: Single cast delegate: Single cast delegate holds the reference of only one method. Multi-cast delegate: A delegate which holds the reference of multiple methods is called multi-cast delegate. A multicast delegate holds the reference of the methods which return type is void.
The differences between events and delegates are given below:
The event comes with its pair of assessors i.e. Add and Remove. Which is assigned and unassigned with a += and -= operator
The event has a restrictive signature and must always be of the form Event(object sender, EventArgs args)
Defined by name - Can be static as well - Access through the name - Supports shortened syntax - A get accessor has no parameters - A set accessor has an implicit value parameter
it is identified by signature - it must be an instance member - Access through index - Doesn’t support shortened syntax - A get accessor has same parameters as it has - A set parameter has the same parameters as it has plus the value param
Destructors are techniques to remove instances of classes as soon as class close. The destructor is used to release unmanaged resources allocated by the object. It is called automatically before an object is destroyed. It cannot be called explicitly. A class can have only one destructor.
The destructor is a special type member function which has the same name as its class name preceded by a tilde (~) sign.
Example:
class DestructorExample { public DestructorExample() { Console.WriteLine("Constructor called"); } //destructor ~DestructorExample() { Console.WriteLine("Destructor called"); } } class Program { static void Main() { DestructorExample T = new DestructorExample(); GC.Collect(); } } Out Put : Constructor called Destructor called
IEnumerable: -
IQueryable: -
Finalize():
Dispose():
C# is a high level, modern, simple, general-purpose and object-oriented programming language that has grown rapidly and is also used widely. C# was developed by Microsoft led by Anders Hejlsberg and his team within the.Net initiative which was approved by Europen Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# has grown enormously with the extensive support from Microsoft helping it to acquire a large following and now it is one of the most popular programming languages in the world. You can use it to create Windows client application, distributed components, XML Web services, database applications, etc.
Being flexible, powerful and well-supported feature has turned C# to become one of the most popular programming languages available. It is the 4th most popular programming language. More than 117,000 C# jobs are advertised each month with an average salary of more than $72,000. Only in the USA, there are more than 6,000 jobs advertised each month with an annual salary of $92,00. According to Payscale an average salary of C# Developer is $66,185. Companies like Intel Corporation, Rhino Agile, TAG Employer Services, and Food Services of America are the companies using C#.
If you are planning to start your career in C#, you need to be well prepared with all the possible C# interview questions which could be asked in a C# interview. These C# Interview Questions will provide you with in-depth knowledge and help you ace your C# interview. These are the C# interview questions have been designed specially to get you familiar with the nature of questions that you might come across during your C# interview.
Going through these C# programming language interview questions will help you to land your dream job. These C# basic interview questions will surely boost your confidence to face an interview and will definitely prepare you to answer the toughest of questions in the best way possible. These C# developer interview questions are suggested by experts and have proven to have great value.
Not only the job aspirants but also the recruiters can also refer these C# basic interview questions to know the right set of questions to assess a candidate. Treat your next C# interview as an entrance to success. Give it your best and get the job. Wish you all the luck and confidence. You can also take up the C# Certification Training to enhance your career further.
Submitted questions and answers are subjecct to review and editing,and may or may not be selected for posting, at the sole discretion of Knowledgehut.