To advertise with us contact on Whatsapp: +923041280395 For guest post email at: [email protected]

C# Interview Questions Best 50+ with Answers

C# Interview Questions Best 50+ with Answers

C# is a programming language that has grown rapidly and is also used widely. C# interview questions help you in preparing interview. C# is in high demand, versatile and supports cross-platform as well. Here are some frequently asked interview questions for freshers as well as experienced C# developers’ candidates to get the right job.

Table of Contents

C# Interview Questions

Below is the list of selected C# interview questions.

Q.1- What is C#?

C# is an object-oriented, type-safe, and managed language that is compiled by .Net framework to generate Microsoft Intermediate Language.

Q.2- What is an Object and a Class?

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.

Q.3- What are the fundamental OOP concepts?

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 behaviour 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.

C# interview questions

Q.4- What is Managed and Unmanaged code?

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.

Q.5- 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.

Q.6- What are the different types of classes in C#?

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.

C# interview questions

Q.7- Explain Code compilation in C#.

There are four steps in the code compilation which include:

  • Compiling the source code into Managed code by C# compiler.
  • Combining the newly created code into assemblies.
  • Loading the Common Language Runtime(CLR).
  • Executing the assembly by CLR.

C# interview questions

Q.8- What are the differences between a Class and a Struct?

Given below are the differences between a Class and a Struct:

Class Struct
Supports Inheritance Does not support Inheritance

Class is Pass by reference (reference type) Struct is Pass by Copy (Value type)

Members are private by default Members are public by default

Good for larger complex objects Good for Small isolated models

Can use a waste collector for memory management Cannot use a Garbage collector and hence no Memory management

Q.9- What is the difference between Virtual method and Abstract method?

A Virtual method must always have a default implementation. However, it can be overridden in the derived class, though not mandatory. It can be overridden using override keyword.

An Abstract method does not have an implementation. It resides in the abstract class. It is mandatory that the derived class implements the abstract method. An override keyword is not necessary here though it can be used.

C# interview questions

Q.10- Explain Namespaces in C#.

They are used to organize large code projects. “System” is the most widely used namespace in C#. We can create our own namespace and use one namespace in another, which are called Nested Namespaces.

They are denoted by the keyword “namespace”.

C# interview questions

Q.11- What is “using” statement in C#?

“Using” Keyword denotes that the particular namespace is being used by the program.

For Example, using System. Here System is a namespace. The class Console is defined under System.  So we can use the console.writeline (“….”) or readline in our program.

C# interview questions

Q.12- Explain Abstraction.

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.

C# interview questions

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.

Q.13- Explain Polymorphism?

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.

C# interview questions

Q.14- How is Exception Handling implemented in C#?

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.

C# interview questions

Q.15- What are C# I/O Classes? What are the commonly used I/O Classes?

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.

Q.16- What are Boxing and Unboxing?

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);

Q.17- What is the difference between Continue and Break Statement?

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.

C# interview questions

Q.18- What is the difference between finally and finalize block?

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.

C# interview questions

Q.19- What is an Array? Give the syntax for a single and multi-dimensional array?

An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.

C# interview questions

For Example:

double numbers = new double[10];

int[] score = new int[4] {25,24,23,25};

A Single dimensional array is a linear array where the variables are stored in a single row. Above example is a Single dimensional array.

Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.

For Example, int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };

Q.20- What is a Jagged Array?

A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.

int[] jaggedArray = new int[4][];

Q.21- Name some properties of Array.

Properties of an Array include:

  • Length – Gets the total number of elements in an array.
  • IsFixedSize – Tells whether the array is fixed in size or not.
  • IsReadOnly – Tells whether the array is read-only or not.

C# interview questions

Q.22- What is an Array Class?

An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace System.

C# interview questions

Q.23- What is a String? What are the properties of a String Class?

A String is a collection of char objects. We can also declare string variables in c#.

string name = “C# Questions”;

A string class in C# represents a string.

The properties of String class are Chars and Length.
Chars get the Char object in the current String.
Length gets the number of objects in the current String.

C# interview questions

Q.24- What is an Escape Sequence? Name some String escape sequences in C#.

An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.

C# interview questions

String escape sequences are as follows:

\n – Newline character
\b – Backspace
\\ – Backslash
\’ – Single quote
\’’ – Double Quote

Q.25- What are the basic String Operations? Explain.

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.

Q.26- What is Parsing? How to Parse a Date Time String?

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 5, 2020”;
DateTime parsedValue = DateTime.Parse(dateTime);

Q.27- What are Events?

Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress and so on.

Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber. An Event should have at least one subscriber else that event is never raised.

Q.28- How to use Delegates with Events?

Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.

Q.29- What do Multicast Delegates mean?

A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.

Q.30- What are Synchronous and Asynchronous operations?

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.

Q.31- What is Reflection in C#?

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.

Q.32- What is a Generic Class?

Generics or Generic class is used to create classes or objects which do not have any specific data type. The data type can be assigned during runtime, i.e when it is used in the program.

Q.33- Explain Get and Set Accessor properties?

Get and Set are called Accessors. These are made use by Properties. A property provides a mechanism to read, write the value of a private field. For accessing that private field, these accessors are used.

Get Property is used to return the value of a property
Set Property accessor is used to set the value.

Q.34- Name some properties of Thread Class.

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.

Q.35- 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 a state stopped.
  • Stopped – Thread has stopped.

Q.36- What is a Deadlock?

A 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.

Q.37- Explain Lock, Monitors, and Mutex Object in Threading.

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.

A 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.

Q.38- What is a Race Condition?

A 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.

Q.39- What is Thread Pooling?

A 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.

System.Threading.ThreadPool namespace has classes which manage the threads in the pool and its operations.

Q.40- What is Serialization?

Serialization is a process of converting a code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.

Any class which is marked with the attribute [Serializable] will be converted to its binary form.

The reverse process of getting the c# code back from the binary form is called Deserialization.

To Serialize an object we need the object to be serialized, a stream which can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.

Q.41- What are the types of Serialization?

The different types of Serialization are: XML serialization, SOAP, and Binary.

  • 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 which can be used by any system that understands SOAP.
  • Binary Serialization – Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.

Q.42- What is an XSD file?

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.

Q.43- Can multiple catch blocks be executed?

No, Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block, and then the code that follows the finally block gets executed.

Q.44- Define Constructors

A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

Q.45-What is the use of ‘using’ statement in C#?

The ‘using’ block is used to obtain a resource and process it and then automatically dispose of when the execution of the block completed.

Q.46- What is the Console application?

A console application is an application that can be run in the command prompt in Windows. For any beginner on .Net, building a console application is ideally the first step, to begin with.

Q.47- Is C# code is managed or unmanaged code?

C# is managed code because Common language runtime can compile C# code to Intermediate language.

Q.48- What is the difference between directcast and ctype?

DirectCast is used to convert the type of object that requires the run-time type to be the same as the specified type in DirectCast.

Ctype is used for conversion where the conversion is defined between the expression and the type.

Q.49- What is the difference between the “throw” and “throw ex” in .NET?

“Throw” statement preserves original error stack whereas “throw ex” have the stack trace from their throw point. It is always advised to use “throw” because it provides more accurate error information.

Q.50-What are C# attributes and its significance?

C# provides developers a way to define declarative tags on certain entities, e.g. Class, method, etc. are called attributes. The attribute’s information can be retrieved at runtime using Reflection.

Q.51- What’s a multicast delegate?

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

Q.52- What is THE difference between “is” and “as” operators in c#?

“is” operator is used to check 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.

Q.53- How we can create an array with non-default values?

We can create an array with non-default values using Enumerable. Repeat.

Q.54- What is the difference between a Struct and a Class?

Structs are value-type variables, and classes are reference types. Structs stored on the Stack causes additional overhead but faster retrieval. Structs cannot be inherited.

Q.55- How can we set the class to be inherited, but prevent the method from being over-ridden?

Declare the class as public and make the method sealed to prevent it from being overridden.

Q.56- What happens if the inherited interfaces have conflicting method names?

Implement is up to you as the method is inside your own class. There might be a problem when the methods from different interfaces expect different data, but as far as compiler cares you’re okay.

If you are interested in getting backlink or placing paid ads, you may contact at [email protected]

Sponsored by WebSoft IT Development Solutions (Private) Limited

Leave a Reply

Your email address will not be published. Required fields are marked *