Top 100 C# interview questions and answers 2020

C# interview questions and answers
HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

The c# programming language provides the rapid application development and It is the best language for writing Microsoft .NET applications. Its syntax is similar to C++ syntax. Here are top Basic and Advanced C# Interview Questions and Answers for Freshers and Experienced Dot Net developers.


C# Basic Interview Questions


1) What is a C# programming language?

C# is a modern, high level, general purpose object oriented programming language. This language is principal language of .Net framework. The design goal of the language was software robustness, durability & programmer productivity. It can be used to create a console application, GUI application, web application both on PC or embedded systems.

2) What are the types of comment in C# with examples?
  1. Single line
    //This is a Single line comment

  2. Multiple line
    /*This is a multiple line comment
    Here you can use more than 1 line*/

  3. XML Comments
    /// This is XML code Comment.
     
3) What is a class in c#?

A class describes all attributes of objects as well as the method that implements the behavior of member object. Basically, it represents a blue print of object. It is a template of an object. A class contains data & behavior of an entity.
Example: Aircraft.
Data: Model number of aircraft, Color of aircraft, category of aircraft etc.
Behavior/Method: Duration of flight, number of passengers etc.

4) What is an object?

An object is an instance of the class. It is a basic unit of the system. An object is an entity that has attributes, behavior & identity. Attributes & behavior of an object is defined by the class definition.

5) What is the relation between class and objects?

They both look very much same but they are not same. The class is definition while the object is the instance of the class created. The class is blue print while objects are actual objects existing in the world.
Example: Car has attributes & method like speed, brake, type of car etc.

6) List some of the advantages of C#?

Following are the advantages of C#

  1. Easy to learn
  2. Object oriented
  3. Component oriented
  4. Part of .NET framework
7) What are IDE’s provided by Microsoft for C# development?

Following are the IDE’s used for C# development

  1. Visual Studio Express (VCE)
  2. Visual Studio (VS)
  3. Visual Web Developer
8) What is the difference between a struct and a class in C#?

Struct & Class both are the user defined data type but have some major differences:

# Struct Class
1. Structure are value type in C# & it inherits from System.ValueType. Classes are reference type & it inherits from the System.Object Type.
2. Structure use stack to store value. classes use heap to store value.
3. Structure can not be declared as protected . Classes can not declare as protected.
4. We can not be able to use inheritance in Structure. We can use inheritance in classes.
5. The struct can have the only constructor. The class can have the constructor and destructor.
6. Structure objects can not destroy using GC. Objects created from classes are terminated using GC.
7. The struct can instantiate without using the new keyword.. The new keyword should be used to create the object for the class.
8. The struct can only inherit the interfaces. The class can inherit the interfaces, abstract classes.
9) What are the similarities between a struct and a class in C#?
  1. Both can have a constructor, method/functions, properties, fields, constants, enumeration, events & event handler.
  2. Structure & classes can implement the interface.
  3. Both of them can have a constructor with & without parameters.
  4. Both can have delegates & events.
10) What is oops and what are the different properties provided by oops?

Oops stands for object oriented programming system. It is a problem-solving technique to think real world problems in terms of objects.

Following are different properties provided by oops


  1. Inheritance: It is a process of forming new class from the existing class.
    Example: A scientific calculator is an extended form of a calculator. Here, the calculator is the parent & scientific calculator is child object.

  2. Polymorphism: The ability to use an operator or functions in different ways giving different meaning to function to the operator is called polymorphism.
    Example: A person is behaving like a Child, professor, student and then as a clerk. This is the power of polymorphism, a single object behaves in different forms.

  3. Encapsulation: Encapsulate means to hide also called as data hiding. Encapsulation is used to hide the code & data in a single unit. It is a process of hiding all the internal details of an object from the outside world.
    Example: Capsule: Capsule which hides medicine inside it.

  4. Abstraction: Abstraction means showing only necessary information & hiding unnecessary information from the user. Abstraction let you focus on what object does instead of how it does it.
    Example: Suppose you have a car, and u are riding car, now when you apply break you know that car is going to stop but you don't know what is the process happened when you applied break. Abstraction means putting all the variables and methods in a class that is necessary.

11) The Differences between Abstraction and Encapsulation in C#?
# Abstraction Encapsulation
1. Abstraction solves the problem at design level. Encapsulation solves the problem at the implementation level.
2. Abstraction is set to focus on the object instead of how it does it. Encapsulation means hiding the internal details or mechanics of how an object does something.
3. Abstraction is used for hiding the unwanted data and giving only relevant data. Encapsulation is hiding the code and data into a single unit to protect the data from the outer world.
4. Abstraction is implemented using interface & abstract class. Encapsulation is implemented using private & protected access modifiers.
5. Abstraction is outer layout in terms of design. Encapsulation is inner layout in terms of implementation.
e.g. Outer Look of an iPhone, like it has a display screen. Inner Implementation detail of an iPhone, how Display Screen are connected with each other using circuits.
12) Explain sealed class in C#?

The sealed class is used to stop the class from being inherited from other classes. If you define a class in C# as "Sealed" & "nonheritable" in VB.NET, then you can not inherit the class further.


13) What are value types in C#?

Value types directly contain data and derived from System.ValueType.
Value types use the stack to store value.
Example: int, float, char, Bool, short


14) What are reference types in C#?

reference types stored the address of memory where data is stored
reference types use the heap to store value.
Example: Class, Interface, String, Object, Delegate, Array

15) What is the difference between value types and reference types?
# Struct Class
1. They are stored on stack. They are stored on heap.
2. Memory is allocated at compile time. Memory is allocated at runtime.
3. The value type is popped on its own from the stack when they go out of scope. Required garbage collector to free memory.
4. Value type contains actual value. Reference type contains reference to a value.
5. Cannot contain null values. However, this can be achieved by nullable types. Can contain null values.
e.g. int, float, char, Bool, short. Class, Interface, String, Object, Delegate, Array.
16) How do you get the size of value type?

using SizeOf operator.
Example: Console.WriteLine("The size of long is {0}.", sizeof(long));
output: The size of long is 8.

17) What are different types of the parameter in c#?

Following are different types of parameter in c#
1. Value parameter(in)
2. Reference parameter (ref)
3. Output parameter(out)
4. Parameter Array(param)

18) What is the difference between “out” and “ref” parameters in C#?

"out" parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.

19) 18. List out the differences between Array and ArrayList in C#?

Array
1. Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime.
2. Arrays belong to System.Array namespace.


ArrayList
1. Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type.
2. Arraylist belongs to System.Collection namespaces

     

20) Why we use keyword "const" in C#.

"Const" keyword is used for making an entity constant.

Example: const string _name = "techstudy"; Once we define a variable as a const then we can’t reassign the value of that variable(string _name).

21) What are Access Modifiers in C#?

Access Modifiers are basically used to control the accessibility of types and members with in the types. In C# there are 5 different types of Access Modifiers.


1. Public: Public is the most common access specifier in C#. It can be accessed from anywhere, that means there is no restriction on accessibility. It is accessible to all classes & projects.


2. Private: The range of the accessibility is limited only within the classes or struct in which they are declared.


3. Protected: All members in the current class & in derived classes can access the variables.


4. Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.


5. Protected Internal: The protected internal access specifier allows a class to hide its member functions & member variables from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.


22) How is the exception handling done in C#?

In C# there is a "try...catch & finally" block to handle the error.

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
}  finally {
   // statements to be executed
}
23) Can we execute multiple catch blocks in C#?

No. Once any exception has occurred it executes specific exception catch block and the control comes out.

24) What is Jagged Array in C#?
You can initialize a jagged array as

int[][] marks = new int[2][]{new int[]{12,13,52},new int[]{56,85,45,89}};

Where, marks is an array of two arrays of integers - marks[0] is an array of 3 integers and marks[1] is an array of 4 integers.
25) What is the purpose of using statement in C#?

using keyword is used to include a namespace in the program. A program generally has multiple using statements.

26) How to sort an array in C#?

Using Array.sort(array) function.

27) Is multiple inheritance supported in C#?

No! C# does not support multiple inheritance.

28) What is the difference between while, do while and for loop?

1) While loop checks for the condition first so it may not even enter into the loop if the condition is false.
2) do while loop executes the content of the loop once before checking the condition of the while.
3) For loop is similar to while loop except, the initialization of variable, condition check & increment happens at one place.

29) What is the difference between "constant" and "readonly" variables in C#?

"Const" keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is always mandatory to constant variables.
"readonly" variable value can be changed during runtime and value to readonly variables can be assigned in the constructor or at the time of declaration.

30) What is the difference between dispose and finalize methods in c#?

Dispose: This method uses interface – "IDisposable" interface & it will free up both managed and unmanaged codes like - database connection, files etc. It belongs to the IDisposable interface. Implement this method when you are writing a custom class that will be used by other users.


Finalize: This method is called internally unlike Dispose method which is called explicitly. It is called by the garbage collector and can’t be called from the code. Finalize belongs to System.Object class. Implement this method when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.

31) What is the difference between string and StringBuilder in c#?
String

The string is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create a new instance in memory to hold the new value.
String belongs to System namespace


=>Example
string str = "hi";
//It creates a new string instance instead of changing the old one
str += "help";
str += "test";


StringBuilder
String builder is mutable. Mutable means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
StringBuilder belongs to System.Text namespace


=> Example
StringBuilder sb = new StringBuilder("");
//It does not creats new instance for every time.
sb.Append("hi");
sb.Append("help ");
string str = sb.ToString();

32) List out some of the exceptions in C#?
Below are some of the exceptions in C#-

1. ArgumentNullException
2. NullReferenceException
3. IndexOutOfRangeException
4. DivideByZeroException
5. StackOverflowException
6. InvalidOperationException etc.

33) What do you mean by the delegate in C#?

Delegates are type safe pointers, unlike function pointers as in C++. A delegate is used to represent the reference to the methods of some return type and parameters.
Delegates are required because they can be used to write much more generic type safe functions.

34) What are the types of delegates in C#?

Following are the types of delegates in C# -
1. Single Delegate
2. Multicast Delegate
3. Generic Delegate

35) What is a multicast delegate?

A delegate having multiple handlers assigned to it is called multicast delegate. Each handler is assigned to a method.

36) What is Nullable Type in C#?

Variable types do not hold null values so to hold the null values we have to use nullable types. nullable types can have values either null or other values as well.
Eg: int? nullvariable = null;

     
37) What do you mean by boxing and unboxing in C#?

Boxing: This is the process of converting from value type to reference type.

Example
int i = 67; // i is a value type
object o = i; // i is boxed
System.Console.WriteLine(i.ToString()); // i is boxed


UnBoxing: It’s the process of converting reference type to value type.

System.Collections.ArrayList list = new System.Collections.ArrayList(); // list is a reference type
int n = 67; // n is a value type
list.Add(n); // n is boxed
n = (int)list[0]; // list[0] is unboxed

38) Can "this" be used within a static method?

We can't use "this" in a static method because we can only use static variables/methods in a static method.

39) Explain is an interface class?

Interface class is an abstract class which has only public abstract methods & the methods only have the declaration and not the definition. These abstract methods must be implemented in the inherited classes.

40) Explain Abstract class?

We create an abstract class when we define a template that needs to be followed by all the derived classes. Abstract class can have implementation which should be implemented in the child class.

41) What is the difference between Interface and Abstract class?
# Abstract class Interface Class
1. Abstract class can have implementation for some of its members or methods. Interface class can not have implementation for any its members.
2. Abstract class can have fields. Interface class can not have fields.
3. Abstract class can inherit from another Abstract class or another interface. Interface class can inherit from another interface class only. Interface cannot inherit from an abstract class.
4. Abstract class members can have access modifiers. Interface class members can not have access modifiers.
5. Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
e.g. Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}.
42) What is the difference between static & dynamic polymorphism?
# Static polymorphism Dynamic polymorphism
1. Method overloading would be an example of static polymorphism. It uses the concept of early binding(Compile time binding). Method Overriding would be an example of dynamic polymorphism. It uses the concept of late binding(Runtime Binding).
2. Static polymorphism is faster than dynamic polymorphism because of early binding. Dynamic polymorphism is faster than static polymorphism because of late binding.
3. Static polymorphism is less flexible as all things execute at compile time. Dynamic polymorphism is more flexible as all things execute at run time.
4. It is achieved by function overloading and operator overloading. It is achieved by abstract classes and virtual functions.
43) What are the ways a method can be overloaded?

Methods can be overloaded using the different order of parameters, data types for the parameter, and using a different number of parameters.

44) Explain 'Virtual' Keyword?

The virtual keyword is used while defining a class to specify that the method and properties of that class can be overridden in derived class.

45) What is generics in C#.NET?

Generics are used to make reusable code classes to decrease the code redundancy, increase type safety and performance. Using generics, we can create a collection of classes. To create a generic collection, System.Collections.Generic namespace should be used.

46) How do you inherit a class into other class in C#?

Colon is used as inheritance operator in C#. Just place a colon and then the class name.


Example: public class DerivedClass : BaseClass

47) What is the difference between is and as operators in c#?

"is" operator is used to checking the compatibility of an object with a given type and it returns the result as Boolean.

"as" operator is used for casting of an object to a type or a class.

48) Is C# code is managed or unmanaged code?

Yes! C# is managed code because it uses Common language runtime(CLR) to compile C# code.

49) What are the differences between static, public and void in C#?

Public: The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.

Static: The keyword static declares that the Main method is a global one and can be called without creating an instance of the class. The compiler stores the address of the method as the entry point and uses this information to begin execution before any objects are created.

Void: The keyword void is a type modifier that states that the Main method does not return any value.

50) What is the difference between methods – “System.Array.Clone()” and “System.Array.CopyTo()” ?

“CopyTo()” method can be used to copy the elements of one array to other.

“Clone()” method is used to create a new array to contain all the elements which are in the original array.

51) Explain Partial Class in C#?

Partial classes concept added in .Net Framework 2.0 & it allows us to split the business logic into multiple files with the same class name along with “partial” keyword.

     
51) What are the collection types can be used in C#?
Following are the collection types in C# -

1. ArrayList
2. Stack
3. Queue
4. SortedList
5. HashTable
6. Bit Array

Threading Questions


52) What is multitasking?

It is a feature of modern OS with which we can run multiple programs at the same time.
Example: Word, Excel etc.

53) What is Multi-Threading?

It is a subset of multitasking. Instead of switching between programs this feature switches between different part of the same program.
Example: Writing in MS-Word and It also checking spelling using spell-checker in the background

54) What is a thread?

It is a basic unit to which OS allocates processor time.
Example: .Net Framework program has at least 2 threads running one is the main program & Second is Garbage collector(GC).

55) How can we change the priority & what the levels of priority provided by .Net?

Syntax to change thread priority

Threading.Priority = Threadpriority.priorityUnit;
Levels of priority
1) Threadpriority.Highest (10)
2) Threadpriority.Abovenormal (7)
3) Threadpriority.Normal(5)
4) Threadpriority.Belownormal(3)
5) Threadpriority.Lowest(1)

56) How can you reference current thread of the method?

"Thread.Currentthread" refers to the current thread running the method.
It is public static property.

57) What is thread.sleep() in threading?

Thread execution can be paused by calling the Thread.Sleep method. This method takes on integer value that determines how long the thread should sleep
Example: Thread.currenttime.sleep(2000) // 2 Seconds

58) How can you make a thread sleep for infinite time?

Thread.sleep(System.Threading.Timeout.Infinite)

To interrupt this sleep method you can call-
Thread.interrupt method

59) What is suspend & Resume in Threading?

It is similar to sleep & interrupts. Suspend allow you to block thread until another thread calls thread.resume.

60) What is the difference between sleep & suspend?

The difference between sleep & suspend is that suspend does not immediately place a thread in a wait state. the thread does not suspend until the .Net runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

61) How to stop the long running thread??

Thread.Abort stops the thread execution at the moment itself.

62) What is Thread.Join in threading?

There are two versions of Thread.join
1) Thread.join()
2) Thread.join(integer) this returns a bool value.


Example: If we have two threads-> Thread1 & thread2 while executing "Thread1" you call "Thread2.Join()". So "Thread1" will wait until "Thread2" has completed its execution and again invoke "Thread1".


Thread.join(integer) ensures that thread does not wait for a long time. once it exceeds the provided specific time, It will start the waiting thread.

63) What is serialization?

If you want to transfer an object through network then you have to convert the object into a stream of bytes. The process of converting an object into a stream of bytes is called serialization.

64) What is object pool in .Net?

Object pool is a container of ready to use objects. It reduce the overhead of creating new objects.

65) What are circular references?

Circular reference is state in which 2 or more resources are interdependent on each other causes the lock condition and make the resources unusable.

66) What is Hashtable in C#?

A Hashtable is a collection of key-value pairs. It contains values based on the key.

67) What is Constructor Overloading in C#?

In Constructor overloading, n number of constructors can be created for the same class. But the signatures of each constructor should always vary


Example

1
2
3
4
5
6
7
public class Student
{
                            public Student() 
 { }
                            public Student(String fullname) 
 { }
}
     
68) What are indexers in C#?

Indexers are known as the smart arrays in C#. It allows the instances of a class to be indexed in the same way as array.


Example
1
public int this[int index] 
69) How to implement singleton design pattern in C#?

In singleton pattern, a class can only have one instance and provides access point to it globally.


Example:
1
2
3
4
Public sealed class Singleton
{
Private static readonly Singleton _instance = new Singleton();
}
70) Name the compiler of C#?

Name of C# Compiler is – CSC.

71) Which string method is used for concatenation of two strings in c#?

“Concat” method of String class is used to concatenate two strings


Example:
1
string.Concat(firstnamestr, lastnamestr)
72) What is the difference between "continue" and "break" statements in C#?

Using break statement, you can 'jump out of a loop' while by using continue statement, you can 'jump over one iteration' and then resume your loop execution.

So Guys, this brings us to the end of this article on C# Interview Questions and answers. I hope this post world helped in adding up to your knowledge. Wishing you all the best for your interview.




Popular Posts