Top 41 C# Interview Questions and Answers [2020]

Hey,  It looks like you have landed on the right place - to grab free interview questions and answers in c# a single spot.  

Trust me you will not regret to spend your time . Why I say this is because the content available here have been picked up from top most ranked companies in the industry standard for C# interview questions and answers with real time examples, for experienced professionals to get placed.

C# Interview Questions and Answers

What is that I promise you here? 

The whole content will soon be available free download e-book PDF format.

Please note that correct answers are highlighted in green color and the rest are options.

Let's get started,

1. If arr is an array of int, how can you obtain the number of elements in arr?


2. Which code block correctly references this class and its static members?  
public class Bird
    public static int NumberOfLegs = 2;
    public static bool CanFly = true;
    public static void BirdDescription()
{ // Do Something } }
Bird.BirdDescription();int numLegs = Bird.NumberOfLegs;bool canFly = Bird.CanFly; 
var bird = new Bird();bird.NumberOfLegs = 2;bird.CanFly = true; 
var bird = Bird.BirdDescription();int numLegs = Bird.NumberOfLegs;bool canFly = Bird.CanFly;
var bird = new Bird();int numLegs = bird.NumberOfLegs;bool canFly = bird.CanFly; 

3.There are multiple calls from a single thread and you must propagate any exceptions back to the calling thread, handling each exception individually. How can this be accomplished? 
By catching Aggregate.TaskException and iterating over its InnerExceptions collection
By starting each task with the optional parameter of .wait() and logging exceptions before continuing with the next task
 By wrapping the multiple tasks within a try/catch block, logging any errors, and running continue() on the next task. 
By catching System.AggregateException and iterating over its InnerExceptions collection.

4.  Consider the following two classes. Which line of code would you use to replace FUNC<TRESULT> methodCall implementation?
public class TestDelegate
    public static void Main()
      OutputTarget output = new OutputTarget();
      if (methodCall())
         Console.WriteLine("File write operation failed.");
public class OutputTarget
   public bool SendToFile()
         string fn = Path.GetTempFileName();
         StreamWriter sw = new StreamWriter(fn);
         sw.WriteLine("Hello, World!");
         return true;
         return false;
Func<bool> methodCall = output.SendToFile; 
Func<bool> methodCall = new output.SendToFile();
Func<bool> methodCall = output.SendToFile();
Func<bool> methodCall = new output(SendToFile());

5.  Which of the following is an example of correctly parsing a date/time string into a DateTime object in .NET? 
string strDate = "6/25/2008", format = "d";
DateTime parsedDate;
parsedDate = DateTime.ParseExact(strDate,format);
string strDate = "Jun 25, 2022";DateTime parsedDate = DateTime.Parse(strDate);
string strDate = "Jun 25, 2022";DateTime parsedDate = new DateTime(strDate);
DateTime strDate = "Jun 25, 2022";DateTime parsedDate = new DateTime.Parse(strDate);
6. Which loop statement will increment the variable x and produce a value of 25 in the Console.WriteLine() statement at the bottom?
int x = 1; do { x++; } while (x < 25);Console.WriteLine("x: " + x);
int x; while (x == 0 || x < 26){ x++; } Console.WriteLine("x: " + x);
int x = 1; do { x++;} while (x <= 25);Console.WriteLine("x: " + x);
7. LINQ's ability to delay the retrieval of data until it is actually needed is called what?
Deferred execution (Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.)
Pending execution
On-demand execution
Real-time execution 

8. Which code block correctly creates an abstract class containing an abstract method?
public abstract class AbstractClassA { public abstract void TDo(); }
public abstract class AbstractClassA{abstract void TDo(); } 
public abstract class AbstractClassA {public abstract void TDo();class MyAbstractClass(){} }
private protected abstract AbstractClassA { public abstract void TDo();}

9. How do you declare a generic method called Test that takes one parameter which must be a value type?
public void Test<T>(T t) where T : struct { /* ... */ }
public void Test<T : struct>(T t) { /* ... */ }
public void Test<T>(T t) where : T is struct { /* ... */ }
public void Test<struct T>(T t) { /* ... */ }

10. Which of the following is an accurate statement regarding the difference between the List<T> class and an array in C#?
Arrays support multiple dimensions while lists do not.
Lists represent a strongly typed list of objects whereas arrays can contain multiple data types.
Arrays use generics and are type-safe versions of lists.
Lists are fixed in size once allocated while arrays are not fixed in size.
11.  Which of the following is an example of correctly parsing a date/time string into a DateTime object in .NET? 
string fact = "C# technology...always get set solution GetSetSolution";
int start = fact.IndexOf("always");
var fact2 = fact.Substring(start);
always get set solution GetSetSolution
C# technology
technology... always
12.  Consider below code. What type must GetCustomerNames() return for this to compile?
string[] allNames = await GetCustomerNames();
13.  When evaluating two string values for equality, which snippet of code will ignore the casing? (example NAME == name)
var areSame = String.Compare(stringValue1, stringValue2, true) == 0 ? "true" : "false";
bool isEqual = stringValue1 == stringValue2;
var areSame = String.Compare(stringValue1,stringValue2) == 0 ? "true" : "false";
bool isEqual = stringValue1.toString() == stringValue2.toString();
14.  You wrote a class MyClass that overrides a base class method void DoSomething(). How can you prevent the MyClass override of DoSomething from being further overridden?
You can declare the method MyClass as sealed override.
Declare the method as private override in MyClass.
Once a method has been overridden, preventing further overrides is not possible.
Declare the method as public virtual sealed in MyClass.
15. Which event would result in an Exception.InnerException being null?
The inner exception value was not supplied to the constructor.
A string exception value was not instantiated with the error handler.
The exception was an unknown error.
The inner exception value was overridden by the exception base class.
16.  Consider the following jagged array, How would you retrieve the value 22 from the array above?
int[][] jaggedArray = new int[][] 
    new int[] { 1, 3, 5, 7, 9 },
    new int[] { 0, 2, 4, 6 },
    new int[] { 11, 22 }
jaggedArray[3, 2];
17.  Review the following class, What steps are required to handle the Number-randomized event in another object?
public class NumberRandomizer
    public NumberRandomizer()
       // perform tasks
    // custom event handler
    public event EventHandler NumberRandomized;
Declare a new instance of the NumberRandomizer class in the object; Attach a custom event handler within the object using +=.
Declare a new instance of the NumberRandomizer class in the event;Attach a custom event within the object using Subscribe().
Extend the calling class with NumberRandomizer; Attach the NumberRandomized event within the object using +=.
Declare a new instance of the NumberRandomizer class in the event;Attach a custom event within the object using Add().

18. What is the main purpose of an extension method?
To add functionality to an existing type without directly modifying that type.
To add functionality to a derived class not available in its base class
To add additional behavior to an existing method
To protect the level of security on some of the methods in the extended class
19. Which type of variable has the property of preserving its value even after it is out of scope?

20. Which method would order a result set in ascending order by the field 'Id'?
var ordered = list.OrderBy(x => x.Id);
var ordered = list.OrderAsc(x => x.Id);
var ordered = list.OrderAscending(x => x.Id);
var ordered = list.Order(x => x.Id);
21. What type of key must you use to group by more than one key in a LINQ query?
22. Which statement describes a benefit of using interfaces as part of a design pattern?
You can always be sure that when a non-abstract class implements your interface it will implement all of its members.
By using interfaces, you can exclude unwanted behavior from multiple classes without removing references to the classes themselves.
Interfaces allow you to deeply couple classes.
Using interfaces adds a layer of security to your application by creating an abstract class implementation of a base class.
23. What is the difference between the Select clause and SelectMany() method in LINQ?
In both the Select clause and SelectMany() method a result value will be generated out of the source of values. 
The difference between both of them is in the result set. The Select clause will generate one value for every source value.
The result value is a collection which is having the same number of elements from the query.
On the other side, theSelectMany() method generates a single result that has a concatenated from the query.
24. What are the different implementations of LINQ?
Following are the different implementations of LINQ:
LINQ to SQL : This component was introduced in .Net framework version 3.5 that gives a run-time mechanism to manipulate relational data as objects.
LINQ to DataSet : This component facilitates to run simpler and faster query over data which is cached in the DataSet object.
LINQ to XML : Provides an in-memory XML programming interface.
LINQ to Objects : It provides the use of LINQ queries with any IEnumerable or IEnumerable(T)collection directly, without the use of an middle LINQ provider or API, like LINQ to SQL or LINQ to XML.
25. Why var keyword is used and when it is the only way to get query result?
var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalized keyword.
The compiler infers the actual type from the static type of the expression used to initialize the variable.
It is must to use the var keyword when we deal with the queries which returns anonymous type.

var results = from t in MyStringData
select new
   NoOfLetter = t.Length,
   CapitalString = t.ToUpper()

foreach (var result in results)
    Console.WriteLine(result.NoOfLetter+ " " +result.CapitalString);

26. What are the pros and cons of LINQ (Language-Integrated Query)?
Pros of LINQ:
LINQ provides the type safety.
Abstraction is provided by LINQ and thus it enable us to use the concept of multi threading.
LINQ is easy to deploy as well as it is easy to understand.
Using .Net debugger we can debug the LINQ code.
LINQ allow us to use more than more one database together.
Cons of LINQ:
In LINQ, it is necessary to process the whole query, and therefore it reduces the performance when we have large and complex queries.
It is generic, while we can use multiple feature of database using stored procedures.
In the case of any change in queries, we have to recompile and redeploy the assembly.

27. What is benefit of using LINQ on Dataset?
The major objective to use LINQ to Dataset is to execute strongly typed queries over Dataset.
Consider the scenario that you require to merge the results from two Datasets, or you require to take a distinct value from a Dataset, then we can use LINQ.
Usually we can use the SQL queries to execute on the database to get the Dataset, but we can’t use SQL queries on a Dataset to retrieve a single value, for which use of ADO.NET features is necessary.
While, in case of LINQ, it supports better dignified way to execute queries on Dataset and gives some new functionalities than ADO.NET.

28. What is the difference between the Take and Skip clauses?
 The Take clause will give you a predefined number of elements.
Suppose if you want to return two elements from an array then you can use Take clause.
The Skip clause will skip the predefined number of elements in the query and returns the remaining elements.
Suppose if you want to skip first five strings in an array of strings and want to retrieve the remaining string then you can use Skip clause

29. Can you tell the advantages of LINQ over stored procedure?
Debugging – LINQ supports .Net debugger, so we can easily debug a LINQ query using .NET debugger but it is not supported by SQL stored procedure so it is hard to debug the stored procedure.
Deployment – To deploy stored procedure it is necessary to write one more script to run them, while LINQ will compile by a single DLL statement and so the deployment will be simple.
Type Safety - As LINQ supports type safety so errors can be type checked in LINQ queries in compile time.
It is better to use LINQ as it enable us to identify the errors while compilation rather than runtime execution.
30. Which are the language extensions in C# 3.0 useful for LINQ?
Lambda Expressions: If we want to create a delegate in LINQ then we can use a Lambda expression.
Anonymous Types: We can use Anonymous types to generate a bunch of read-only properties in a single object in which it is not necessary to define a type first.
Object Initializers: C# 3.0 supports Object Initializers to create and initialize the objects in single step.
Implicitly Typed Variables: To achieve this we can use “var” keyword.
31. Can you describe delegate in detail?
A delegate is an object that can refer to a method. It means that it can hold a reference to a method. The method can be called through this reference or we can say that a delegate can invoke the method to which it refers. The same delegate can be used to call different methods during the runtime of a program by simply changing the method to which the delegate refers. The main advantage of a delegate is that it invokes the method at run time rather than compile time. Delegate in C# is similar to a function pointer in C/C++.
Important Note:A delegate can call only those methods that have same signature and return type as delegate.
This delegate can only call those methods that have string return type and take argument as string.
A delegate type is declared using the keyword delegate. The prototype of a delegate declaration is given below example,

delegate ret-type name(parameter-list);
delegate string StrDemo(string str);

32. What is Dependency Injection?
Dependency injection (DI) is a pattern where objects are not responsible for creating their own dependencies. 
 Here is an simple interface example to motivate DI.

interface ILogger 
    void LogMessage(string message);

Without Dependency Injection

class SomeComponent
    ILogger _logger = new FileLogger(@"C:\logs\log.txt");

    public void DoSomething()

With Dependency Injection

class SomeComponent
    ILogger _logger;

    // Inject ILogger into the object.
    public SomeComponent(ILogger logger)
        if (logger == null)
            throw new NullReferenceException("logger");
        _logger = logger;

    public void DoSomething()
33. Find first three words in a sentence?
There are two ways to get the first three words in a sentence. Example 1 is old way of doing words split whereas Example 2 is one line of code which is very easy to get result. 

Example 1

 string input= "Get Set Solution is free source to learn";
 string output=string.Empty;
 foreach (string s in input.Split(' ').Take(3))
     output += s;
Output  GetSetSolution

Example 2

string input= "Get Set Solution is free source now";           
string strResult = string.Join("",input.Split(' ').Take(3));
Output GetSetSolution

34. How do you reverse each word and lower case in a sentence?

string input = "Get Set Solution"; 
string.Join(" ", input.Split(' ').Select(x => new String(x.Reverse().ToArray()).ToLower()));
Output teg tes noitulos

35. How do you reverse each word change to lower case and then arrange in alphabet order of sentence?

string input = "Get Set Solution"; 
string.Join(" ", input.Split(' ').Select(x => new String(x.Reverse().OrderBy(a => a.ToString()).ToArray()).ToLower()));}
Output egt est ilnostu

36. How do you find first char of each word in a sentence, and make those char to upper case?

string input = "Get Set Solution is free source available";
string.Join(" ", input.Split(' ').Select(x => x[0].ToString().ToUpper()));
Output G S S I F S A

37. How do you split each word in a sentence and make last char of a word to upper case?
 There are two ways to get result, find example 1 and example 2.
Example 1
string sentence= "Get Set Solution";
foreach(var item in input.Split(' '))
   sentence += string.Join("", char.ToUpper(item[0]), (item.Length > 1) ? item.Substring(1, item.Length - 2) : "", (item.Length > 1) ? char.ToUpper(item[item.Length - 1]).ToString() : "", " ");
} return sentence
Output GeT SeT SolutioN
Example 2
string sentence= "Get Set Solution";
foreach(var item in sentence.Split(' '))
{ wordFirstChar = item.Replace(item[0], char.ToUpper(item[0])); wordLastChar = wordFirstChar.Replace(wordFirstChar[wordFirstChar.Length - 1], char.ToUpper(wordFirstChar[wordFirstChar.Length - 1])); output += string.Join(" ", wordLastChar, " "); } return sentence;
Output GeT SeT SolutioN

38. Can you find second largest number in an array of integer? 
The code blow gets the second largest number which is 4
var numbers = new int[] { 3, 5, 1, 5, 4 };
var result=numbers.OrderByDescending(x=>x).Distinct().Skip(1).First();
Output 4

39. Can you find factorial value of given any number?
In mathematics, finding a factorial number is essential and here we go how we  apply in computing. char ! is represented as factorial.
Let's say you want to find what is factorial value of number 5 !
 5! = 5 x 4 x 3 x 2 x 1 = 120.
IEnumerable<int> ints = Enumerable.Range(1, 5);
int factorial = ints.Aggregate((f, s) => f * s);
Which correctly gives 120. ‘f’ is the aggregate value and ‘s’ is the current element in the lambda expression.
The following is performed step by step:
 First iteration passes in f = 1 and s = 2, which yields 1×2 = 2
 Second iteration f is the result of the first iteration, i.e. 2 and s will be the second element, 
  i.e. 3, yielding 2×3 = 6
Then it continues with f = 6 from the second operation and taking 4 from the integer sequence, giving 6×4 = 24
Finally we get 24×5 = 120

40. Can you reverse a string or word without c# in-built function?
 //Reverse a string
public static class ReverseString
     //string x ="Hai";
    public static string Reverse(string x) 
        string result = "";
        for (int i = x.Length - 1; i >= 0; i--)
            result += x[i];
        return result;
Output iaH

41. Can you override ToString() in a class?
public override ToString() => "This is an object";


The above interview questions are for freshers and experienced, you have gone through entire article describes about C# interview question and answers as Part-1. There are more to come in Part-2 with real time scenarios.