17/Sep/2024 | 18 minutes to read
dotnet
Here is a List of essential C# Interview Questions and Answers for Freshers and mid level of Experienced Professionals. All answers for these C# questions are explained in a simple and easiest way. These basic, advanced and latest C# questions will help you to clear your next Job interview.
These interview questions are targeted for C# Programming language, an object-oriented language. A .NET Developer or Testing Professional must know the answers of these frequently asked C# interview questions to clear the interview.
1. What do you understand about Top-level statements in C#?
2. Explain the primary constructors?
3. How will you enable nullable reference types in a C# application?
enable
to your .csproj
file #nullable enable
at the top of your file. #nullable enable
around the code section.
4. How will you differentiate readonly
, const
and static
variables in c#?
5. What are the three characteristics of Object Oriented Programming?
6. What is the difference between in
, ref
and out
keywords?
7. Why does c# not support multiple Inheritance?
To understand this, First you need to understand the Diamond problem:
The Diamond problem (It's also referred to as the "deadly diamond of death") is an ambiguity that occurs when two classes B and C inherit from Class A and class D inherits from both B and C.
If a method in class D calls a method defined in A(and does not override the method), and B and C have already overridden that method differently, then from which class does it inherit: B or C?
8. What is method shadowing or method hiding in C#?
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 says
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)
So modify the code as below.
class DC : BC
{
new public void Display()
{
System.Console.WriteLine("DC::Display");
}
}
7. How will you differentiate var
, object
and dynamic
keywords in C#.
class Program
{
static void Main(string[] args)
{
var x = 10;
object y = 20;
dynamic z = 30;
x = "test"; // Error - Cannot implicitly convert type 'string' to 'int'
y = "test";
y = y - 10; //Error Operator '-' cannot be applied to operands of type 'object' and 'int'
z = "test";
z = z - 10;
Console.WriteLine("{0},{1},{2}",x,y,z);
Console.ReadLine();
}
void display(var x){} // Error CS0825 - The contextual keyword 'var' may only appear within a in local variable declaration or script code.
void display(object x){}
void disp1(dynamic x){}
}
8. Can Virtual or Abstract members be declared private in C#?
No, It will throw a compile time error.
virtual void display() // will throw error here
{
// Implementation
}
9. What is Boxing and Unboxing in C# ?
int a = 13;
// The below line assigns the value of int a to object o, it's boxing.
object o = a;
Now you can assign the value of o to integer a, it's unboxing.
o = 13;
a = (int)o; // unboxing
For more visit Boxing and Unboxing in C#.
10. What is Method Overloading in C#?
void check(int x)
{
// Implementation
}
void check(float x)
{
// Implementation
}
void check(int x, int y)
{
// Implementation
}
In the above example method name is the same 'check' in all three cases but method signature is different.
11. What is Value Type and Reference Type in C#?
12. What are the new features in C# 8.0?
To know more about C# 8.0 new features visit What's new in C# 8.0
13. How will you differentiate Abstraction and Encapsulation in C#?
BankAccount
base class creates an abstraction or defines
the behavior for the Bank Account concept. Now you can create any type of bank account like saving, just by deriving your new class 'SavingAccount' from this 'BankAccount'
base class.
BankAccount
class can contain some private members to hide
the data from the code outside of this 'BankAccount' class.
14. Differentiate Abstract class and Interface in C#? Explain the usage of interface?
15. What is Polymorphism? Explain the static and Dynamic Polymorphism in C#?
public class Shape
{
}
public class Circle : Shape
{
}
public class Rectangle : Shape
{
}
var shapes = new List
{
new Rectangle(), new Triangle(), new Circle()
};
A o1 = new A();
o1.disp();
B o2 = new B();
o2.disp();
A o3 = new B(); // here
o3.disp(); // derived class method will be executed by calling base class method
16. Can Abstract class have a constructor in C#? 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 in C#.
The above code will compile successfully. In C#, we can add Abstract and Sealed keywords with the override keyword.
17. What is the use of the sealed
keyword in C#?
class C {}
sealed class D : C {} // other classes will not be able to inherit from class D.
You can use a sealed modifier to methods and properties in your class which are overriding methods and properties from base class. Using this way other classes will
derive from your class and will not be able to override sealed methods and properties.
For more visit C# sealed.
18. What is the difference between abstract
and virtual
keywords ?
Both virtual
and abstract
are the modifiers in C#. They have different use cases.
abstract
class can contain abstract members and non-abstract members as well.19. Explain string interpolation in C#.
var name = "Microsoft";
Console.WriteLine($"Hello {name}"); // O/P: Hello Microsoft
For more visit C# String Interpolation.
20. Explain about String Immutability in C#.
Once you create a String object in C#, It can not be modified. When you perform any operation like appending then you get a new instance of a modified String
object instead of modifying the actual instance value. So String Objects are immutable in C#. If you are planning to perform many append operations on a string object then use
StringBuilder
class.
For more visit Immutable String in C#.
21. How to compare two String Objects in C#?
You should use the Compare
method to determine the relationship of two strings in sorting order and if you want to test for equality of two strings then
you should Instance Equals
or static Equals
method with a StringComparison
type parameter.
For more about string operations visit
String in C#.
21. What is nullable value type? How to read value from a nullable value type in C#?
22. What are the new features in C# 7.0?
To know more about C# 7.0 new features visit What's new in C# 7.3
23. What is Covariance and Contravariance in C#?
Fore more Covariance and Contravariance in C#
24. What points (related to try, catch and finally) you should keep in mind while implementing exception handling in C#?
25. What is Generics in C#? What are the benefits of Generics?
For more visit Generics in C#.
26. Explain Memory management (Heap vs Stack) in a C# Program.
For more visit Heaping vs Stacking in .NET and C# Memory Management.
29. How does Garbage Collection work in C#? Explain Generations.
Garbage Collection (GC) is an automatic memory management mechanism in C# that reclaims the memory occupied by objects that are no longer in use by the application. When an object is created, it is allocated memory on the managed heap. The GC periodically checks the managed heap for objects that are no longer reachable (objects with no active references). These unreachable objects are marked for collection, and their memory is reclaimed for future allocations. GC plays a crucial role in managing memory efficiently and preventing memory leaks in C# applications.
For more visit Garbage Collection in C#
and How GC manages memory?
30. What is using
statement in C#?
IDisposable
or IAsyncDisposable
interface.
IDisposable
or IAsyncDisposable
objects. When the object's lifetime
is limited to a single method then you should use the 'using' statement to declare and instantiate disposable objects. An object declared inside a using statement can not
be modified or re-assigned meaning it is read-only. It disposes the object in case of any exception or it's equivalent to try-finally implementation.
string message=@"Hello I am good , first line
How are you, second line
I am fine third line";
using var reader = new StringReader(message);
string? line;
do {
line = reader.ReadLine();
Console.WriteLine(line);
} while(line != null);
For more visit using statement.
27. What is IDisposable
Interface in C#? How to implement the dispose method?
For more visit Finalizer & Dispose.
28. Explain Dispose Pattern in C#.
31. What are the Finalizers in C#? Explain SupressFinalize()
method.
For more visit Finalizers in C#
32. Explain different kinds of collections in C#.
33. What are the benefits of Generic Collections?
33. What is the difference between IEnumerable and IQueryable in C#? When would you use one over the other?
IEnumerable and IQueryable are both interfaces in C# used for working with collections and querying data, but they have different purposes and characteristics. IEnumerable represents a sequence of elements that can be iterated over, and its implementations (e.g., List
34. Explain algorithmic complexity of collections in C#.
37. Explain internal working of Dictionary or Hashtable.
For more visit Dictionary or Hashtable internal working Hashtable internal working.
35. When to use a thread-safe collection in C#?
36. How to perform comparisons and sorts within collections?
37. Explain Iterators in C#.
38. What is the difference between the Equality operator ==
and Equals()
method in C#?
39. What is the use of new
keyword apart from creating a new object in C#?
40. What are the extension methods in C#?
public static class StringPowerUps
{
// this is the signature to create an extension method
public static string Shout(this string text)
{
return text.ToUpper() + "!";
}
}
// usage of extemsion method
string normalString = "hello world";
string loudString = normalString.Shout();
Console.WriteLine(loudString); // Outputs: HELLO WORLD!
In C#, extension methods must be defined within a static class. This is a requirement for the compiler to recognize and process extension methods correctly.
41. Explain the Lambda expressions in C#?
42. What are the anonymous methods in C#?
43. Explain Partial class and methods.
44. What are the different ways to pass parameters in C#?
45. How will you differentiate EXE
and DLL
files?
46. What is the DLL hell Problem?
47. Explain the concept of Parallel Processing, Concurrency, and Async Programming in .NET?
For more visit Parallel Processing, Concurrency, and Async Programming in C#.
48. How will you differentiate Thread vs Task?
48. What is volatile
keyword in C#?
In C#, volatile keyword indicates that multiple executing threads which are executing at the same time can modify the value of a field. The fields which are declared volatile are observed by all the threads for volatile writes by any other thread in the same order in which it was performed. All reads and writes to memory locations of volatile fields may be rearranged by the compiler, the runtime and even hardware for performance reasons. For more visit C# volatile.
49. What is async
and await
in C#?
async & await
keywords are used to implement asynchronous operations in C#. These operations could be either
I/O bound (such as web service taking time to download some content or file) or CPU bound (any expensive calculation by CPU). Task
means - the ongoing work. When the control reaches the awaited expression, the method is suspended until the task gets completed because we are waiting for the result
of the awaited task.
public async Task ExampleMethodAsync()
{
//...
string contents = await httpClient.GetStringAsync(requestUrl);
}
For more about Asynchronous programming visit
Asynchronous programming with async and await
and async await C#.
50. How to handle exceptions in Async methods?
For more visit Exceptions in async methods.
50. Explain C# 6.0 new features.
C# 6.0 has many new features. For more visit What's new in C# 6.0
51. What is Deep copy and Shallow copy?
For more visit Cloning;
52. What is the use of yield
keywords in C#?
53. How User-defined conversions work in C#?
54. Differentiate Action vs Func in C#.
class Test
{
// Func Example
public string CreateNamefromName1()
{
return CreateName(GetName1);
}
public string CreateNameFromName2()
{
return CreateName(GetName2);
}
private string CreateName(Func createName)
{
var name1 = "hello";
var name2 = "testing";
return createName(name1, name2);
}
private string GetName1(string arg1, string arg2) => $"{arg1}-{arg2}";
private string GetName2(string arg1, string arg2) => $"{arg1}::{arg2}";
}
55. Explain the use of below interfaces in C#?
49. Print the output of the below program? Error Line
will throw any error in below code?
class A
{
public virtual void display()
{ Console.WriteLine("A - display method"); }
}
class B:A
{
public override void display()
{ Console.WriteLine("B - display method"); }
}
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 method
B - display method
B - display method
55. What will be the output here? or will it throw any error?
public void display()
{
int x = 0;
int y = 10;
try
{
int z = y / x;
}
catch (Exception)
{
throw;
}
catch (DivideByZeroException)
{
throw;
}
finally
{
}
}
56. Print the output of this program?
int a = 0;
try
{
int x = 4;
int y ;
try
{
y = x / a;
}
catch (Exception e)
{
Console.WriteLine("inner ex");
//throw; // Line 1
//throw e; // Line 2
//throw new Exception("divide by 0"); // Line 3
}
}
catch (Exception ex)
{
Console.WriteLine("outer ex");
throw ex;
}
Let's see the output:
1. How much will you rate yourself in C#?
When you attend an interview, Interviewer may ask you to rate yourself in a specific Technology like C#, So It's depend on your knowledge and work experience in C#. The interviewer expects a realistic self-evaluation aligned with your qualifications.
2. What challenges did you face while working on C#?
The challenges faced while working on C# projects are highly dependent on one's specific work experience and the technology involved. You should explain any relevant challenges you encountered related to C# during your previous projects.
3. What was your role in the last Project related to C#?
This question is commonly asked in interviews to understand your specific responsibilities and the functionalities you implemented using C# in your previous projects. Your answer should highlight your role, the tasks you were assigned, and the C# features or techniques you utilized to accomplish those tasks.
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?
Whether a candidate has completed any C# certification or training is optional. While certifications and training are not essential requirements, they can be advantageous to have.
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 info@qfles.com. Our IT Expert team will find the best answer and will update on the portal. In case we find any new C# questions, we will update the same here.