You are on page 1of 14

C# is the most popular and widely used programming language for developing web

applications, desktop applications, and mobile apps. This article contains the top 20
C# interview questions and answers, in order to prepare you for the interview.

1. What is C#?
C# pronounced as "See Sharp". It is an object-oriented programing
language developed by Microsoft, which runs under the .NET platform. Its syntaxes are
similar to C++ or Java. The most recent version of C# is 7.3 which is introduced with
Visual Studio 2017 update 15.7. C# is widely used for developing web applications,
desktop applications, mobile apps, and games, etc. Now, C# can be run on Mac,
Linux/Unix and Windows using .NET Core.

2. Explain the evolution history of C#?


The evolution history of C# is given below:

3. What features are added to different versions of C#?


The following features are added to different versions of C#:

C# 1.0
 Managed Code
 IDE - Visual Studio .NET 2002, 2003
 .NET Framework - 1.0, 1.1

C# 2.0
 Generics
 Static Classes
 Partial types
 Anonymous methods
 Iterators
 Nullable types
 Asymmetric Property and Indexer Accessors
 Delegate Inference
 Covariance and Contra-variance
 .NET Framework - 2.0

C# 3.0
 Implicit types (var)
 Partial Methods
 Object and collection initializers
 Auto-Implemented properties
 Anonymous types
 Extension methods
 Query expressions
 Lambda expressions
 Expression trees
 IDE - Visual Studio 2008

 .NET Framework - 3.5

C# 4.0
 Dynamic binding
 Named arguments
 Generic Covariance and Contra-variance
 COM Interop
 IDE -Visual Studio 2010
 .NET Framework - 4.0

C# 5.0
 Asynchronous methods
 Caller info attributes
 IDE - Visual Studio 2012, 2013
 .NET Framework - 4.5, 4.5.1

C# 6.0
 Auto Property Initializer
 Primary Constructors
 Dictionary Initializer
 Declaration Expressions
 Static Using
 await inside catch block
 Exception Filters
 Null-Conditional Operator
 IDE - Visual Studio 2015
 .NET Framework - 4.6

C# 7.0
 Local Functions
 Literal improvements
 Digit Separators
 Pattern matching
 ref returns and ref Locals
 Throw Expressions
 Expression Bodied Members
 Deconstruction

 IDE - Visual Studio 2017

4. What is Asynchronous Method?


In C# 5.0 two keywords async and await are introduced which allow you to write
asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0,
for writing asynchronous code, you need to define callbacks to capture what happens
after an asynchronous process finish. These keywords are used in a combination of
each other and an await operator is applied to a one or more than one expression of
an async method. An async method returns a Task or Task<TResult> that represents
the ongoing work of the method.
1. public async Task<IEnumerable<Product>> GetProductList()
2. {
3. HttpClient client = new HttpClient();
4. Uri address = new Uri("http://dotnettricks.com/");
5. client.BaseAddress = address;
6.
7. HttpResponseMessage response = await client.GetAsync("myservice/pro
duct/ProductList");
8.
9. if (response.IsSuccessStatusCode)
10. {
11. var list = await response.Content.ReadAsAsync<IEnumerable<Pr
oduct>>();
12. return list;
13. }
14. else
15. {
16. return null;
17. }
18. }
19.

5. Explain the C# code execution process?


C# code execution life cycle diagram is shown as follows :
6. What are the advantages of C# over Java?
The advantage of C# over java is given below :
 C# offers cross-language interoperability or mixed language programming (Java
lacking).
 C#directly supports windows operating system (Java lacking).
 C# is component-oriented language integrated support for the writing of
software support.
 C# support pointer as unsafe (Java lacking it).

7. What is Datatype?
Data Type refers to the type of data that can be stored in a variable. It also specifies
how much memory would be allocated to a variable and the operations that can be
performed on that variable. C# is rich in data type which is broadly divided into two
categories.
 Value Type
 Reference Type
8. What is the difference between value type and reference
type?
Value Type: A value type variable stores actual values. Values types are of two types -
built-in and user-defined. Value types are stored in a stack and derived from
System.ValueType class.
0.
1. int x = 10;
2. char ch = 'a';
3.

Reference Type: A reference type variable stores a reference to the actual value.
Typically, a reference type contains a pointer to another memory location that stores
the actual data. Reference types are of two types - built-in and user-defined. Reference
types are stored in a heap and derived from System. Object class.

9. What are Nullable types?


Value types that can accept a normal value or a null value are referred to as Nullable
types. These are instances of the Nullable struct. For example, A Nullable<bool>
pronounced as "Nullable of bool" and can have the values true, false or null. Nullable
types can also be defined using ? type modifier. This token is placed immediately after
the value type being defined as nullable.
0. //assigning normal value
1. Nullable<bool> flag = true;
2. //Or You can also define as
3. bool? flag = true;
4.
5. //assigning normal value
6. Nullable<int> x = 20;
7. //Or You can also define as
8. int? x = 20;
9.

Note
You should not declare a string as nullable since it is implicitly nullable. Hence,
declaring a string type like string? firstNamecauses a compile-time error.

10. What is ?? Operator in C#?


The ?? Operator is called the null-coalescing operator. It is used to define a default
value for nullable value types or reference types. It returns the left-hand operand if the
operand is not null; otherwise, it returns the right operand.
0. int? x = null;
1. int y = -1;
2.
3. // when x is null, z = y
4. // when x is not null, z = x
5. int z = x ?? y; // where x and y are left and right operand
6.

11. What is the dynamic type in C#?


The dynamic type was introduced in C# 4.0. Dynamic type variables are declared using
the "dynamic" keyword. A dynamic type variable bypasses the compile-time type
checking and its operations are resolved at run time. In dynamic type, if the operations
are not valid then the exception would be thrown at run time, not at compile time.
0. class Program
1. {
2. public static void Main()
3. {
4. dynamic d = 1; //assigning integer
5. Console.WriteLine(d);
6.
7. d = "Hi Dynamic"; //assigning string to the same variable d
8. Console.WriteLine(d);
9.
10. d = TestData(); //assigning method result to the same variab
le d
11. Console.WriteLine(d);
12.
13. // You can call anything on a dynamic variable,
14. // but it may result in a runtime error
15. Console.WriteLine(d.Error);
16. }
17.
18. public static double TestData()
19. {
20. return 12.80;
21. }
22. }
23.
24. /* Output
25.
26. 10
27. Hi Dynamic
28. 12.80
29. RuntimeBinderException was unhandled, 'double' does not cont
ain a definition for 'Error'
30. */
31.

12. What are the differences between ref and out


parameters?
Ref - The ref keyword makes an argument (data) to be passed by reference to the
corresponding parameter. Hence, when the value of the parameter is changed in the
method, it gets reflected in the calling method.

Key Points
 The Passing argument must be initialized before passing to the method using the
ref keyword.
 A Property cannot be passed as ref parameter since internally property is a
function.
Out – The out keyword also makes an argument (data) to be passed by reference to
the corresponding parameter, but that argument can be passed without assigning any
value to it.

Key Points
 The passing argument must be initialized in the passed method before it returns
back to the calling method.
 Also, a Property cannot be passed as out parameter since internally property is a
function.
For example, A program uses ref and out keyword as method argument.
4. public class MyClass
5. {
6. public static void Main()
7. {
8. int arg1 = 0; //must be initialized
9. int arg2;
10.
11. MyMethod1(ref arg1);
12. Console.WriteLine(arg1); // Now 2!
13.
14. MyMethod2(out arg2);
15. Console.WriteLine(arg2); // Now 3!
16. }
17.
18. static void MyMethod1(ref int param1)
19. {
20. param1 = 1; //initialization is optional
21. }
22. static void MyMethod2(out int param2)
23. {
24. param2 = 2; //must be initialized
25. }
26. }
27.
28. /* Output
29. 1
30. 2
31. */
32.

13. What do you mean by Class?


A Class is a user-defined data structure that contains data members (fields, properties,
events, and indexer), member function and nested class type. Basically, a class is :
 A user-defined data type.
 A reference type.
 A tag or template for an object.
3. class Book
4. {
5. //Attributes
6. int BookId;
7. string Title;
8. string Author;
9. string Subject;
10. double Price;
11.
12. //Parametrized constructor to set book details
13. public Book(int bookId, string title, string author, string s
ubject, double price)
14. {
15. BookId = bookId;
16. Title = title;
17. Author = author;
18. Subject = subject;
19. Price = price;
20. }
21.
22. //Behaviours
23. public void showDetails()
24. {
25. Console.WriteLine("\n########## Book Details ##########");
26.
27. Console.WriteLine("BookId :{0}", BookId);
28. Console.WriteLine("Title : {0}", Title);
29. Console.WriteLine("Author : {0}", Author);
30. Console.WriteLine("Subject : {0}", Subject);
31. Console.WriteLine("Price : {0}", Price);
32. }
33. }
34.
35. public class Program
36. {
37. public static void Main(string[] args)
38. {
39. //object creation and initialization
40. Book objBook1 = new Book(1, "ASP.Net Interview Questions & A
nswers", "Shailendra Chauhan", ".NET Interview", 500);
41. Book objBook2 = new Book(2, "C# Interview Questions & Answer
s", "Shailendra Chauhan", ".NET Interview", 400);
42.
43. //calling class
44. objBook1.showDetails();
45. objBook2.showDetails();
46.
47. Console.ReadKey();
48. }
49. }
50.
51. /* Output
52.
53. ########## Book Details ##########
54. BookId :1
55. Title : ASP.Net Interview Questions & Answers
56. Author : Shailendra Chauhan
57. Subject : .NET Interview
58. Price : 500
59.
60. ########## Book Details ##########
61. BookId :2
62. Title : C# Interview Questions & Answers
63. Author : Shailendra Chauhan
64. Subject : .NET Interview
65. Price : 400
66. */
67.

14. What do you mean by Object?


An object is a representative of the class and is responsible for memory allocation of
its data members and member functions. An object is a real-world entity having
attributes (data members) and behaviors (member functions).
For example, a student object can have attributes name, address, and contact number.
It performs activities attending class, giving exam, etc.

15. What is Constructor?


A constructor is a special type of function/method which has the same name as its
class. The constructor is invoked whenever an object of a class is created. It is called
constructor since it constructs the values of the class data members.

Key points
 It is a special function/method because its name is the same as the class.
 It can be overloaded the same as normal methods.
 It is automatically invoked as soon as the object of the class is created.
 It does not return a value, not even a void type.

16. What are the different types of constructors?


There are three types of the constructor – default constructor, parameterized
constructor, and copy constructor. But C# does not support copy constructor.

0. Default Constructor

A default constructor has no parameter. When a class has no constructor, a default


constructor is served by the compiler to that class.

1. Parameterized Constructor

The parameterized constructor has one or more arguments and used to assign
values to instance variables of the class.
1. class Example
2. {
3. double num1, num2;
4.
5. #region Constructor Overloading
6.
7. //Default Constructor
8. public Example()
9. {
10. Console.WriteLine("This is a default constructor!");
11. }
12.
13. //Parameterized Constructor
14. public Example(int a, int b)
15. {
16. num1 = a;
17. num2 = b;
18. Console.WriteLine("This is a parameterized constructor!");
19. }
20.
21. //Parameterized Constructor
22. public Example(double a, double b)
23. {
24. num1 = a;
25. num2 = b;
26. Console.WriteLine("This is a parameterized constructor!");
27. }
28. #endregion
29.
30. public void ShowResult()
31. {
32. double result = num1 + num2;
33. Console.WriteLine("Result: {0}", result);
34. }
35. }
36.
37. class Program
38. {
39. static void Main()
40. {
41. Example obj1 = new Example(); //default constructor called
42. Example obj2 = new Example(4, 5); //parameterized constructo
r called
43. Example obj3 = new Example(4.2, 5.2); //parameterized constr
uctor called
44.
45. obj2.ShowResult();
46. obj3.ShowResult();
47. Console.Read();
48. }
49. }
50.
51. /* OutPut
52. This is a default constructor!
53. This is a parameterized constructor!
54. This is a parameterized constructor!
55. Result: 9
56. Result: 9.4
57. */
58.

2. Copy Constructor
This constructor is used to copy the entire values of an object to another object.
But C# does not support copy constructor.

17. What is Destructor?


The destructor is a special type member function/method which has the same name
as its class name preceded by a tilde (~) sign. 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.
class Example
{
public Example()
{
Console.WriteLine("Constructor called");
}

//destructor
~Example()
{
Console.WriteLine("Destructor called to destroy the instance");
}
}

class Program
{
static void Main()
{
Example T = new Example();
GC.Collect();
}
}
/*Output

Constructor called.
Destructor called to destroy the instance

*/

18. What is finalize () method?


Finalize method is used to free unmanaged resources like files, database connections,
COM, etc. held by an object before that object is destroyed. Internally, it is called by
Garbage Collector and cannot be called by user code. Finalize method belongs to
Object class in C#.
You should implement it when you have unmanaged resources in your code and want
to make sure that these resources are freed when the Garbage collection happens.
// Implementing Finalize method
class Example
{
public Example()
{
Console.WriteLine("Constructor called");
}

//At runtime C# destructor is automatically Converted to Finalize method.


~Example()
{
//TO DO: clean up unmanaged objects
}
}

19. What are Generics in C#?


Generics were introduced in C# 2.0. Generics allow you to define type-safe classes,
interfaces, methods, events, delegates, and generic collections without compromising
type safety, performance, or productivity. In generics, a generic type parameter is
supplied between the open (<) and close (>) brackets and which makes it strongly
typed collections i.e. generics collections contain only similar types of objects.

20. What is Multithreading in C#?


Multithreading allows you to perform concurrent processing so that you can do more
than one operation at a time. The .NET Framework System. Threading namespace is
used to perform threading in C#.

For example, you can use one thread to monitor input from the user, second thread to
perform background tasks, third thread to process user input and fourth thread to
show the output of the third thread processing.

You might also like