C# (pronounced as C Sharp) is one of the famous and widely used Object Oriented Programming languages. This article is focused on the most frequently asked and important C# Interview Questions and Answers for freshers as well as an experienced software professional.
These questions are gathered based on actual interview experience. Let’s begin to C# interview questions and answers.
Frequently asked C# Interview Questions and Answers
Que 1. What is C#?
Answer: C# is an object-oriented programming language developed by Microsoft as part of its .Net initiative.
Que 2. What is OOP (Object Oriented Programming)?
Answer: Object-Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic.
OOP allows decomposition of a problem into several entities i.e. objects and then builds data and functions around these objects.
Associated functions can only access the data of the objects.
Que 3. What are the fundamental OOP Concepts in C#?
- Abstraction: Represent the essential feature without representing the background details
- Encapsulation: Wrapping up a data member and a method together into a single unit
- Inheritance: Object reusability
- Polymorphism: Many forms of a single object
What is Class and Object?
Class: Class is mandatory for representing data in any OOP language such as C#. A class is a core in C# or any Object-Oriented programming language. A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data. Use the “class” keyword flowed by class name to create a class.
Example:
class Student
{
}
Object: Objects are the basic run-time entities of an object-oriented system. They may represent a person, a car, or any item that the program must handle.
An object is an instance of a class
A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.
When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.
When an object is created without the new operator, the memory will not be allocated in the heap, that means instance will not be created and the object in the stack contains the value null.
When an object is null then members of the class cannot be accessed by using that object.
Example:
class Student
{
}
Student studentObject = new Student();
studentObject is the object of the Student class. We can access data members and methods of the Student class by using student objects.
Que 4. What is an Interface?
- An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.
- An interface may define static methods, which must have an implementation.
- Another way to achieve abstraction in C#, is with interfaces
interface IPerson
{
void Address();
}
public class Student : IPerson
{
public void Address()
{
Console.WriteLine("The is Student Address!");
}
}
public class Employee : IPerson
{
public void Address()
{
Console.WriteLine("The is Employee Address!");
}
}
static void Main(string[] args)
{
Student student = new Student();
student.Address();
Employee employee = new Employee();
employee.Address();
Console.ReadLine();
}
Output:
Que 5. What is a Destructor in C#?
~Student()
{
Console.WriteLine("Student class Destructor!");
}
Que 6. What is a Struct in C#?
- This is used to hold small date values.
- In Struct, members are public by default.
- No memory management for Struct.
struct Student
{
public int Id;
public string Name;
public string Address;
public Student(int id, string name, string address)
{
Id = id;
Name = name;
Address = address;
}
}
static void Main(string[] args)
{
Student student = new Student(1, "First Student", "100 Main Road, City, ST, 12345");
Console.WriteLine("Student Details:\n Id: {0}\n Name: {1}\n Address: {2}", student.Id, student.Name, student.Address);
Console.ReadLine();
}
Que 7. What is difference between Class and Struct in C#?
Answer: Following are the differences between Class and Struct in C#:
Comparison | Class | Struct |
---|---|---|
Type | Class is Pass by reference (reference type) | Struct is Pass by Copy (Value type) |
Inheritance | Class supports Inheritance | Struct does not supports Inheritance |
Implementation | It's implemented by implementing the IDisposable interface Dispose() method. | It's implemented with the help of a destructor in C++ & C#. |
Default Accessibility Modifiers | Members are private by default in Class | Members are public by default in Struct |
Memory Management | Use Garbage collector for memory management | Cannot use Garbage Collector so no memory management |
Destructor | Class can have a Destructor | Struct doesn't have Destructor |
Que 8. What is difference between class and interface in C#?
Answer: Following are the differences between Class and Struct in C#:
Comparison | Class | Interface |
---|---|---|
Nature | Class has definition and implementation | Struct is Pass by Copy (Value type) |
Inheritance | Class supports Inheritance | Struct does not supports Inheritance |
Constructor | A Class contains constructor | An Interface does not contain constructor |
Accessibility Modifier | A Class can have accessibility modifier for the subs, properties and functions | An Interface cannot to have accessibility modifier. By default, everything is public |
Members | A Class can contain data members and methods with the complete definition | An Interface contains the only signature of members. |
Static Members | I Class can contain static members | An Interface cannot contain static members |
Que 9. What are the different types of classes in C#?
Answer: Following are the different types of class in C# are:
- Partial Class: Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.
- Sealed Class: It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.
- Abstract Class: It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.
- Static Class: It is a class that does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.
Que 10. What happens if the inherited interfaces have conflicting method names?
Example:
interface iInterface1
{
void Show();
}
interface iInterface2
{
void Show();
}
class Student : iInterface1, iInterface2
{
void iInterface1.Show()
{
Console.WriteLine("For iInterface1!");
}
void iInterface2.Show()
{
Console.WriteLine("For iInterface2!");
}
}
static void Main(string[] args)
{
iInterface1 obj1 = new Student();
iInterface1 obj12 = new Student();
iInterface2 obj2 = new Student();
obj1.Show();
obj12.Show();
obj2.Show();
Console.ReadLine();
}
Output:
This is one of the tricky C# Interview Questions. You have to be very careful while giving the answer.
Que 11. What is Boxing and Unboxing in C#?
//Example:
int intValue = 10;
object boxedValue = intValue;
//Example:
int unBoxing = Convert.ToInt32(boxedValue);
Que 12. What is Method Signature in C#?
Answer: The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
The important part here is that the return type of a method does not belong to its signature. So, you can’t overload methods that differ by return type only!
This is one of the frequently asked C# Interview Questions for the freshers and 1-2 years experienced software professional.
Que 13. How Exception Handling is implemented in C#?
Answer: Exception handling is done using the following four keywords in C#:
- try – Contains a block of code for which an exception will be checked.
- catch – It is a program that catches an exception with the help of an exception handler.
- finally – It is a block of code written to execute regardless of whether an exception is caught or not.
- Throw – Throws an exception when a problem occurs.
Que 14. What is the difference between finally and finalize block in C#?
finalize method is called just before garbage collection. It is used to perform cleanup operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.
Que 15. What is the difference between the Virtual method and the Abstract method in C#?
Answer:
Virtual Method: The virtual method must always have a default implementation. It can be overridden in the derived class, though not mandatory. An override keyword must be used to override the method in the derived class.
Abstract Method: The abstract method does not have an implementation. It resides in the abstract class. The derived class must implement the abstract method. An override keyword is not necessary here though it can be used.
Learn more about virtual keyword here
Learn more about abstract keyword here
Continue to C# Interview Questions and Answers
Que 16. Difference between ref and out keyword?
Examples:
//out
class OutExample
{
static void Method(out int i)
{
i = 10;
}
static void Main()
{
int value;
Method(out value);
//output: 10
}
}
//ref
class RefExample
{
static void Method(ref int i)
{
i = i + 10;
}
static void Main()
{
int val = 1;
Method(ref val);
Console.WriteLine(val);
//output: 11
}
}
Although variables passed as an out argument need not be initialized before being passed, the calling method is required to assign a value before the method returns.
The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore, methods cannot be overloaded if one method takes a ref argument and the other takes an out argument.
Que 17. What is a static method in C#?
- Static methods are called by using the class name, not the instance of the class.
- A static method can be invoked directly from the class level
- We can overload static methods in C#
class Student
{
public static void Test()
{
Console.WriteLine("Testing staatic method in C#");
}
}
static void Main(string[] args)
{
Student.Test();
Console.ReadLine();
}
The Console class and its Read and Write methods are an example of static methods. The following code example calls Console.WriteLine and Console.ReadKey methods without creating an instance of the Console class.
Again, this is one of the important and frequently asked C# Interview Questions.
Que 18. What is the extension method?
Example:
public static class MyMathExtension
{
public static int factorial(this int x)
{
if (x <= 1) return 1;
if (x == 2) return 2;
else
return x * factorial(x - 1);
}
}
static void Main(string[] args)
{
int x = 4;
Console.WriteLine("Output: " + x.factorial());
Console.ReadLine();
}
Tips in Extension Methods Usage:
- This keyword must be the first parameter in the extension method parameter list.
- Extension methods are used extensively in C# 3.0 and a further version specially for LINQ extensions in C#, for example:
int[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(g => g);
- Here, order by is a sample for extension method from an instance of IEnumerable<T> interface, the expression inside the parenthesis is a lambda expression.
- It is important to note that extension methods can’t access the private methods in the extended type.
- If you want to add new methods to a type, you don’t have the source code for it, the ideal solution is to use and implement extension methods of that type.
- If you create extension methods that have the same signature methods inside the type you are extending, then the extension methods will never be called.
Que 19. What is an Array in C#?
Single Dimensional Array: A Single dimensional array is a linear array where the variables are stored in a single row.
Example:
int[] obj = new int[10];
int[] singleDArray = new int[5] { 5, 10, 15, 20, 25 };
Example:
int[,] multiDArrays = new int[3, 2] { {4, 2 }, {3, 2 }, {7, 4 } };
Important Properties of an Array:
- Length: Gets the total number of elements in an array.
- IsFixedSize: Flag to indicate whether the array is fixed in size or not.
- IsReadOnly: Flag to indicate whether the array is read-only or not.
Que 20. What is a Jagged Array?
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[3] { 2, 4, 6};
jaggedArray[1] = new int[4] { 3, 4, 7, 9 };
jaggedArray[3] = new int[2] { 4, 8};
Que 21. What is Serialization in C#?
- Answer: Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called Deserialization.
Any class which is marked with the attribute [Serializable] will be converted to its binary form.
To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.
Types of Serialization:
- XML serialization: It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.
- SOAP: Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.
- Binary Serialization: Allows any code to be converted to its binary form. It can serialize and restore public and non-public properties. It is faster and occupies less space.
Uses for Serialization:
Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Developers can perform the following action by using serialization:
- Sending the object to a remote application by using a web service
- Passing an object from one domain to another
- Passing an object through a firewall as a JSON or XML string
- Maintaining security or user-specific information across applications
Que 22. What is LINQ? And how to use it in C#?
Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
Examples:
LINQ extension:
using System;
using System. Linq;
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 3, 5, 7 };
Console.WriteLine("Average: " + array.Average());
}
}
using System;
using System. Linq;
class Program
{
static void Main(string[] args)
{
int[] intArray = { 1, 2, 3, 4, 7, 8 };
var elements = from element in intArray
orderby element descending
where element > 2
select element;
Console.Write("Descending Order: ");
foreach (var element in elements) // Enumerate.
{
Console.Write(element + " ");
}
Console.WriteLine();
}
}
Que 23. What is Lambda Expression in C#?
Examples:
delegate int del(int i);
static void Main(string[] args)
{
del delObj = x => x * x;
int j = delObj(5);
}
//Expression tree type:
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
Expression<del> obj = x => x * x;
}
}
The => operator has the same precedence as an assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.
LINQ and Lambda are not only very important C# Interview Questions but also very commonly used in the development.
Que 24. What is a Delegate in C#?
The best way to understand delegates is to think of them as a class. Just like a class, we can declare the delegate anywhere with whatever access level required. And to use a delegate you must have an instance of the delegate class.
Delegates provide a way to define and execute callbacks. Their flexibility allows you to define the exact signature of the callback, and that information becomes part of the delegate type itself.
- Delegates are type-safe, object-oriented and secure
- Delegate types are derived from the
- Delegate class in the .NET Framework.
- They have a signature and a return type.
- Both Delegate and the method that it refers to can have the same signature.
- Delegates can point to either static or instance methods.
- Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime.
- Delegates can call methods synchronously and asynchronously.
class Program
{
//Delegate Declaration
public delegate int AddNumbers(int a, int b);
static void Main(string[] args)
{
// After the declaration of a delegate, the object must be created of the delegate using
//the new keyword.
AddNumbers delObj = new AddNumbers(AddOperation);
var total = delObj(3, 2);
Console.WriteLine("Addition of two numbers: " + total.ToString());
Console.ReadLine();
}
private static int AddOperation(int fnumber, int snumber)
{
return fnumber + snumber;
}
}
Main() which creates an object of the delegate, then the object can be assigned to AddOperation() as it has the same signature as that of the delegate.
Output:
Types of Delegates:
- Single Delegate: A delegate that can call a single method.
- Multicast Delegate: A delegate who can call multiple methods. + and – operators are used to subscribing and unsubscribing respectively.
- Generic Delegate: It does not require an instance of a delegate to be defined. It is of three types, Action, Funcs, and Predicate.
Que 25. What are Events in C#?
Programmatically, a class that raises an event is called a publisher, and a class that response/receives the event is called a subscriber. An event should have at least one subscriber else that event is never raised.
Delegates are used to declare Events. public delegate void Notification(); public event Notification notifyEvent;
Example:
namespace TestApp
{
public delegate string EventHandler(string str);
class Program
{
public event EventHandler myEvent;
public Program()
{
this.myEvent += SayHello;
}
private string SayHello(string txt)
{
return "Hello " + txt;
}
static void Main(string[] args)
{
Program obj = new Program();
string result = obj.myEvent("User!");
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Learn more about C# Delegates and Events here
Summary:
These are frequently asked C# interview questions and answers that every experience software professional or beginner should learn. This topic will be very helpful to everyone to prepare technical interview.
Continue learning: Useful links for Technical Interview Questions and Answers
- .NET Interview Question and Answers
- Azure Interview Questions and Answers
- WEB API Interview Questions and Answers
- ASP.NET Interview Questions and Answers
- AWS Interview Questions and Answers
- SQL Interview Questions and Answers
- Angular Interview Questions and Answers
- React Interview Questions and Answers
- JavaScript Interview Questions and Answers
- JQuery Interview Questions and Answers
- Behavioral Questions and Answers