Top 50 C# Interview Questions And Answers

Top 50 C# Interview Questions And Answers: Here are the top interview questions of C# language. Be prepared for the interview. You can download the entire questions in a pdf format. so guys All the best for your interview.

1) What is an Object and a Class?

Ans: A Class is an encapsulation of properties and methods that are used to represent a real-time entity. It is a data structure that brings all the instances together in a single unit.

An Object in an instance of a Class. Technically, it is just a block of memory allocated that can be stored in the form of Variables, Array or a Collection.

2) What are the fundamental OOP concepts?

Ans: The four fundamental concepts of Object Oriented Programming are:

  • Encapsulation – The Internal representation of an object is hidden from the view outside object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.
  • Abstraction – It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.
  • Inheritance – It is the ability to create new classes from another class. It is done by accessing, modifying and extending the behavior of objects in the parent class.
  • Polymorphism – The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.

3) What is Managed and Unmanaged code?

Ans: Managed code is a code which is executed by CLR (Common Language Runtime) i.e all application code based on .Net Platform. It is considered as managed because of the .Net framework which internally uses the garbage collector to clear up the unused memory.

Unmanaged code is any code that is executed by application runtime of any other framework apart from.Net. The application runtime will take care of memory, security and other performance operations.

4) What is an Interface?

Ans: An Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.

5) What are the different types of classes in C#?

Ans: 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 which 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 which 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.

6) What are the different types of constructors in C#?

Basically, there are five types of constructors:

  • Static constructor
  • Private constructor
  • Copy constructor
  • Default constructor
  • Parameterized constructor

7) What is static constructor?

A static constructor is used to initialize static data members as soon as the class is referenced the first time.


8) What is method overloading in C#?

Method overloading is mechanism to create multiple methods with the same name and unique signature in the same class. When you go for compilation, the compiler uses overload resolution to determine the specific method to be invoked.


9) Is overriding of a function possible in the same class?

No


10) What is array?

Array is a set of related instances either value or reference types.

There are three types of array supported by C#:

  • Single Dimensional Array: It contains a single row. It is also known as vector array.
  • Multi Dimensional Array: It is rectangular and contains rows and columns.
  • Jagged Array: It also contains rows and columns but it has an irregular shape.

11) Explain Abstraction.

Ans: Abstraction is one of the OOP concepts. It is used to display only the essential features of the class and hides the unnecessary information.

Let us take an Example of a Car:

A driver of the car should know the details about the Car such as color, name, mirror, steering, gear, brake, etc. What he doesn’t have to know is an Internal engine, Exhaust system.

So, Abstraction helps in knowing what is necessary and hiding the internal details from the outside world. Hiding of the internal information can be achieved by declaring such parameters as Private using the private keyword.

12) Explain Polymorphism?

Ans: Programmatically, Polymorphism means same method but different implementations.

It is of 2 types, Compile-time and Runtime.

Compile time polymorphism is achieved by operator overloading.

Runtime polymorphism is achieved by overriding. Inheritance and Virtual functions are used during Runtime Polymorphism.

For Example, If a class has a method Void Add(), polymorphism is achieved by Overloading the method, that is, void Add(int a, int b), void Add(int add) are all overloaded methods.

13) How is Exception Handling implemented in C#?

Ans: Exception handling is done using 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 exception handler.
  • finally – It is a block of code written to execute regardless whether an exception is caught or not.
  • Throw – Throws an exception when a problem occurs.

14) What are C# I/O Classes? What are the commonly used I/O Classes?

Ans: Top 50 C# Interview Questions And Answers: C# has System.IO namespace, consisting of classes that are used to perform various operations on files like creating, deleting, opening, closing, etc.

Some commonly used I/O classes are:

  • File – Helps in manipulating a file.
  • StreamWriter – Used for writing characters to a stream.
  • StreamReader – Used for reading characters to a stream.
  • StringWriter – Used for reading a string buffer.
  • StringReader – Used for writing a string buffer.
  • Path – Used for performing operations related to path information.

15) What is serialization?

Top 50 C# Interview Questions And Answers: If you want to transport 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.


16) How to declare a property in a class?

  1. int m_PersonID = 0;  
  2. public int PersonID  
  3. {  
  4. get { return m_PersonID; }  
  5. set { m_PersonID = value; }  
  6. }  

17) What is the difference between early binding and late binding in C#?

Early binding and late binding are the concept of polymorphism. There are two types of polymorphism in C#.

  • Compile Time Polymorphism: It is also known as early binding.
  • Run Time Polymorphism: It is also known as late binding or method overriding or dynamic polymorphism.

18) What are Boxing and Unboxing?

Ans: Converting a value type to reference type is called Boxing.

For Example:

int Value1 -= 10;

//————Boxing——————//

object boxedValue = Value1;

Explicit conversion of same reference type (created by boxing) back to value type is called Unboxing.

For Example:

//————UnBoxing——————//

int UnBoxing = int (boxedValue);

19) What is the difference between Continue and Break Statement?

Ans: Break statement breaks the loop. It makes the control of the program to exit the loop. Continue statement makes the control of the program to exit only the current iteration. It does not break the loop.

20) What is the difference between finally and finalize block?

Ans: finally block is called after the execution of try and catch block. It is used for exception handling. Regardless of whether an exception is caught or not, this block of code will be executed. Usually, this block will have clean-up code.

finalize method is called just before garbage collection. It is used to perform clean up operations of Unmanaged code. It is automatically called when a given instance is not subsequently called.

21. What is difference between late binding and early binding in C#?

Early Binding and late Binding concepts belong to polymorphism in C#. Polymorphism is the feature of object oriented programming that allows a language to use same name in different forms. For example, a method name Add that can add integers, doubles, and decimals.

Polymorphism we have 2 different types to achieve that: 

  • Compile Time also known as Early Binding or Overloading.
  • Run Time also known as Late Binding or Overriding.

Compile Time Polymorphism or Early BindingIn Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.

Run Time Polymorphism or Late Binding

Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword. 

22. What are the differences between IEnumerable and IQueryable?

Top 50 C# Interview Questions And Answers: Before we go into the differences, let’s learn what the IEnumerable and IQueryable are.

IEnumerable

Is the parent interface for all non-generic collections in System. Collections namespace like ArrayList, HastTable, etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.

IQueryable
As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider’s data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of “executing an expression tree” is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

23) What is delegate in C#?

A delegate in C# is an object that holds the reference to a method. It is like function pointer in C++.


24) What is Hashtable?

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


25) What is Reflection?

Reflection allows us to get metadata and assemblies of an object at runtime.


26) What is Garbage Collection?

Garbage Collection is a process of releasing memory automatically occupied by objects which are no longer accessible.

27) What are Regular expressions? Search a string using regular expressions?

Ans: Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals. Regex is used for string parsing and replacing the character string.

28) What are the basic String Operations? Explain.

Ans: Top 50 C# Interview Questions And Answers:Some of the basic string operations are:

  • Concatenate –Two strings can be concatenated either by using System.String.Concat or by using + operator.
  • Modify – Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
  • Compare – System.StringComparison() is used to compare two strings, either case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
  • Search – StartWith, EndsWith methods are used to search a particular string.

29) What is Parsing? How to Parse a Date Time String?

Ans: Top 50 C# Interview Questions And Answers:Parsing is converting a string into another data type.

For Example:

string text = “500”;

int num = int.Parse(text);

500 is an integer. So, Parse method converts the string 500 into its own base type, i.e int.

Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);

30) What is a Delegate? Explain.

Ans: Delegate is a variable that holds the reference to a method. Hence it is a function pointer of reference type. All Delegates are derived from System.Delegate namespace. Both Delegate and the method that it refers to can have the same signature.

31. What is a multicast delegate in c#?

Delegate is one of the base types in .NET. Delegate is a class, which is used to create and invoke delegates at runtime.

A delegate in C# allows developers to treat methods as objects and invoke them from their code.

32. Difference between Equality Operator (==) and Equals() Method in C#

Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.

33) What are the different types of Delegates?

Ans: The Different types of Delegates are:

Single Delegate – A delegate which can call a single method.

Multicast Delegate – A delegate which can call multiple methods. + and – operators are used to subscribe and unsubscribe respectively.

Generic Delegate – It does not require an instance of delegate to be defined. It is of three types, Action, Funcs and Predicate.

  • Action– In the above example of delegates and events, we can replace the definition of delegate and event using Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result

Public delegate void deathInfo();

Public event deathInfo deathDate;

//Replacing with Action//

Public event Action deathDate;

Action implicitly refers to a delegate.

  • Func – A Func delegate defines a method that can be called on arguments and returns a result.

Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);

  •  Predicate – Defines a method that can be called on arguments and always returns the bool.

Predicate<string> myDel is same as delegate bool myDel(string s);

34) What do Multicast Delegates mean?

Ans: Top 50 C# Interview Questions And Answers: A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.

Consider the Example from question 32.

There are two subscribers for deathEvent, GetPatInfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.

35) Explain Publishers and Subscribers in Events.

Ans: A Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event as discussed in the above questions.

From the Example in Question 32, Class Patient is the Publisher class. It is generating an Event deathEvent, which the other classes receive.

Subscribers capture the message of the type that it is interested in. Again, from the Example of Question 32, Class Insurance and Bank are Subscribers. They are interested in event deathEvent of type void.

36) What are Synchronous and Asynchronous operations?

Ans: Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time.

Asynchronous call waits for the method to complete before continuing with the program flow. Synchronous programming badly affects the UI operations, when the user tries to perform time-consuming operations since only one thread will be used.

In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.

37) What is Reflection in C#?

Ans: Reflection is the ability of a code to access the metadata of the assembly during runtime. A program reflects upon itself and uses the metadata to inform the user or modify its behavior. Metadata refers to information about objects, methods.

The namespace System.Reflection contains methods and classes that manage the information of all the loaded types and methods. It is mainly used for windows applications, for Example, to view the properties of a button in a windows form.

The MemberInfo object of the class reflection is used to discover the attributes associated with a class.

Reflection is implemented in two steps, first, we get the type of the object, and then we use the type to identify members such as methods and properties.

To get type of a class, we can simply use

Type mytype = myClass.GetType();

Once we have a type of class, the other information of the class can be easily accessed.

System.Reflection.MemberInfo Info = mytype.GetMethod(“AddNumbers”);

Above statement tries to find a method with name AddNumbers in the class myClass.

38) Describe Accessibility Modifiers in C#

Answer Top 50 C# Interview Questions And Answers.
Access modifiers are keywords used to specify the declared accessibility of a member or a type.

Access modifiers are keywords used to specify the scope of accessibility of a member of a type or the type itself. For example, a public class is accessible to the entire world, while an internal class may be accessible to the assembly only.

Why to use access modifiers?

Access modifiers are an integral part of object-oriented programming. Access modifiers are used to implement encapsulation of OOP. Access modifiers allow you to define who does or who doesn’t have access to certain features.

39) What is a Virtual Method in C#?

Answer
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method’s basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

Virtual Method

  1. By default, methods are non-virtual. We can’t override a non-virtual method.
  2. We can’t use the virtual modifier with the static, abstract, private or override modifiers.

40) What is a Thread? What is Multithreading?

Ans: Top 50 C# Interview Questions And Answers: A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.

Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.

41) Name some properties of Thread Class.

Ans: Few Properties of thread class are:

  • IsAlive – contains value True when a thread is Active.
  • Name – Can return the name of the thread. Also, can set a name for the thread.
  • Priority – returns the prioritized value of the task set by the operating system.
  • IsBackground – gets or sets a value which indicates whether a thread should be a background process or foreground.
  • ThreadState– describes the thread state.

42) What are the different states of a Thread?

Different states of a thread are:

  • Unstarted – Thread is created.
  • Running – Thread starts execution.
  • WaitSleepJoin – Thread calls sleep, calls wait on another object and calls join on another thread.
  • Suspended – Thread has been suspended.
  • Aborted – Thread is dead but not changed to state stopped.
  • Stopped – Thread has stopped.

43) What is the use of the “using” statement in C#?

There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let’s explain!

  1. using Directive
    Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page. Adding a namespace can be done in the following two ways:
  2. Using Statement
    This is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.

44) What is a Deadlock?

Ans: Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.

Here a Shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.

45) Explain Lock, Monitors, and Mutex Object in Threading.

Ans: Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.

Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.

Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.

Monitor.Enter(ObjA); 
try { }
Finally {Monitor.Exit(ObjA));}

46) What is a Race Condition?

Ans: Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.

If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value to X, the last value written to X will be saved.

47) What is Thread Pooling?

Ans: Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.

48) What is LINQ in C#?

Answer

LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .NET languages with a syntax similar to a SQL query

LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.

Advantages of LINQ 

  1. LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ we can query database, XML as well as collections. 
  2. Compile time syntax checking.
  3. It allows you to query collections like arrays, enumerable classes etc in the native language of your application, like VB or C# in much the same way as you would query a database using SQL.

49) What is File Handling in C#.Net?

Answer

The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory structure. The Directory and File directly extends System.Object and supports the creation, copying, moving and deletion of files using various static methods. They only contain static methods and are never instantiated. The FileInfo and DirecotryInfo types are derived from the abstract class FileSystemInfo type and they are typically, employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static.

50) What is an XSD file?

Ans: Top 50 C# Interview Questions And Answers: An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.

Xsd.exe tool converts the files to XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.

Top 50 C# Interview Questions And Answers Free Download PDF 2019