YouTube Icon

Interview Questions.

Top C# Interview Questions and Answers - Sep 08, 2021

fluid

Top C# Interview Questions and Answers

Debuting lower back in 2000, C# has succeeded in turning into one of the leading programming languages. As a multi-paradigm programming language, C# additionally has some features of practical programming that takes its usefulness and flexibility to a step further.

C# Interview Questions and Answers

In the subsequent section, we've enlisted the maximum essential C# interview questions. These questions prepare you for your next C# interview in addition to enhancing your C# expertise and letting you compare your modern-day C# knowledge.

Question: What is C#? Write its capabilities

Answer: C# is an item-orientated programming language that was developed via Microsoft in 2000. It is supported by extraordinary running systems. C# is the primary language that is used to create .Net software program applications. It permits us to create Windows UI apps, backend services, controls, libraries, android apps, and even blockchain applications. C# works at the idea of classes and gadgets just like Java.

Some of the C# capabilities are as follows:

Follows structured approach

Parameters passing is simple

Code can be compiled on a distinctive platform

Open-supply

Object-oriented

Flexible and scalable 

Question: Explain what are classes and gadgets in C#?

Answer: C# is an item-oriented language and lessons are its basis. A elegance normally depicts the structure of records, how records is saved and managed within a application. A class has its personal homes, techniques, and different gadgets that define the class.

Objects are the real-global entity having some traits and is created the use of the class example. These instructions define the type of the defined item.

For instance, if we remember a software that covers the object associated with the e-book. We name the elegance a Book which has  homes: call and the author. In real programming, Vedas is an item and an instance of the class Book.

Question: Describe the specific C# classes in detail.

Answer:  There are four styles of classes that we are able to use in C#:

Static Class: It is the sort of elegance that can't be instantiated, in different words, we can't create an object of that elegance the usage of the new keyword and the magnificence participants can be called at once the usage of their magnificence call.

Abstract Class: Abstract lessons are declared the usage of the summary key-word. Objects cannot be created for abstract training. If you want to apply it then it have to be inherited in a subclass. You can without difficulty define summary or non-summary techniques within an Abstract magnificence. The strategies inside the abstract class can either have an implementation or no implementation.

Partial Class: It is a type of class that permits dividing their residences, methods, and events into more than one supply files, and at assemble time these documents are blended into a unmarried elegance.

Sealed Class:  One can't inherit a sealed class from another magnificence and restricts the magnificence homes. Any get right of entry to modifiers cannot be applied to the sealed class. 

Question: Explain different get admission to modifiers in C#?

Answer: These are the keywords that help to define the accessibility of sophistication, member, and information kind within the software. These key phrases are used to restrict the use of a few records manipulation done by way of different instructions. There are 4 styles of get entry to modifiers- public, private, protected, and inner. These modifiers define 6 other accessibility tiers whilst operating together- public, covered, inner, covered internal, non-public, and private protected.

Below is the access chart of the modifiers.

   

PUBLIC PROTECTED INTERNAL PROTECTED INTERNAL PRIVATE PRIVATE PROTECTED
Complete program Yes No No No No No
Derived types within the current assembly Yes Yes No Yes No Yes
Using  class Yes Yes Yes Yes Yes Yes
Current assembly Yes No Yes Yes No No
Derived data types Yes Yes No Yes No No

Question: How can you describe object-orientated ideas in detail?

Answer:  C# is an object-orientated programming language that helps 4 OOP ideas.

Encapsulation: defines the binding collectively code and the information and continues it safe from any manipulation performed by using different packages and training. It is a field that forestalls code and statistics from being accessed by way of some other software that is defined outside the box.

Abstraction: this concept of object-orientated protects everything apart from the applicable data about any created object with the intention to increase performance and security inside the program.

Inheritance: Inheritance is applied in such a manner where one object uses the residences of some other item. 

Polymorphism: is a feature that lets in one interface to act as a base magnificence for other lessons. This idea is regularly expressed as a "single interface however a couple of moves". 

Question: Explain how code gets compiled in C#?

Answer: It takes 4 steps to get a code to get compiled in C#. Below are the steps:

First, collect the source code inside the managed code well matched with the C# compiler.

Second, integrate the above newly created code into assemblies.

Third, load the CLR.

Last, execute the meeting by CLR to generate the output.

Question: What is destroy and keep statements in C#, give an explanation for?

Answer:  Below is the variations:

Break Continue
You can use break statements in both switch and loop (for, while, and do-while ) statements. You can use continue statements only in the loop (for, while, do) statements.
The switch or loop statements terminate at the moment the break statement is executed and it ends abruptly from there. You cannot make a continue statement terminate the loop, it carries on the loop to go to the next iteration level without executing the immediate next step.
The loop or switch exits immediately from the inner loop when the compiler encounters a break statement and comes out of the inner loop. A continue that is placed inside a nested loop within a switch causes the next loop iteration.

Question: How you could give an explanation for the usage of ‘the usage of’ statements in C# in element.

Answer:  The using statement is used to govern the usage of one or greater assets which can be getting used inside the program. The sources are continuously ate up and released. The principal function of this declaration is to manipulate unused sources and launch them automatically. Once the object is created that is the use of the aid and whilst you are carried out you make certain that the object’s dispose technique is known as to launch the assets utilized by that item, that is where the usage of statements works nicely.

For example:

using (MyResource abc = new MyResource())
{
 abc.program();
}
Gets translated to,
MyResource abc= new MyResource();
try
{
 myRes.program();
}
finally
{
 // Check for a null resource.
 if (abc!= null)
     // Call the object's Dispose method.
     ((IDisposable)abc).Dispose();
}

Question: Describe the C# put off the method in detail.

Answer: Dispose of the approach: The disposeof() approach releases the unused assets via an item of the class. The unused resources like files, statistics connections, and so on. This method is asserted within the interface referred to as IDisposable that is carried out with the aid of the class via defining the interface IDisposable body. Dispose technique is not known as robotically, the programmer has to put in force it manually for the efficient usage of the sources.

Question: Explain in element the finalize approach in C#?

Answer: Finalize method- The finalize () technique is described in the object class which is used for cleanup sports. This approach is normally referred to as by the rubbish collector on every occasion the reference of any object is not used for a long term. Garbage collector frees that managed assets routinely but in case you want to unfastened the unused resources like filehandle, information connection, and so forth., then you have to enforce the finalize technique manually.

Question: How you could outline the exception handling in C#?

Answer: An exception is a raised problem that can occur during the execution of this system. Handling exceptions gives a easy way to pass the control inside the program each time an exception is raised. C# exceptions are treated with the aid of using 4 key phrases and people are try, catch, eventually, throw.

Attempt: a raised exception finds a particular block of code to get dealt with. There is no restriction on the quantity of capture blocks that you'll use to your application to deal with unique kinds of exception raised.

Capture: you may cope with the raised exception inside this seize block. You can mention the stairs that you need to do to clear up the error or you can ignore the mistake by way of suppressing it by means of the code.

Finally: no matter the mistake, if you nonetheless want a few set of instructions to get displayed then you may use those statements within the subsequently block and it'll display it on the screen.

Throw: you could throw an exception the usage of the throw declaration. It will show the form of error you have become.

Syntax:

try {
//exception handling starts with try block
} catch( ExceptionName ea1 ) {
   // errors are handled within the catch block
} catch( ExceptionName e2 ) {
   // more catch block
} catch( ExceptionName eN ) {
   // more catch block to handle multiple exception raised
} finally {
   // last block of the exception handling
} 

Question: Explain the idea of Destructor in element. Explain it with an example.

Answer:  A destructor is a member that works simply the opposite of the constructor. Unlike constructors, destructors specially delete the object. The destructor call must match precisely with the magnificence call just like a constructor. A destructor block usually starts with the tilde (~) symbol.

Syntax:

~class_name()
{
//code
}

A destructor is called routinely:

while the program finishes its execution.

Whenever a scope of the program ends that defines a local variable.

Whenever you name the delete operator from your application.

Question: Define method overloading with instance.

Answer: Method overloading permits programmers to use multiple techniques but with the equal name. Every described approach within a software may be differentiated on the premise of the range and the kind of approach arguments. It is a idea based on polymorphism.

Method overloading may be finished through the subsequent:

By converting the quantity of parameters in the given technique

By converting the order of parameters exceeded to a way

By the use of one of a kind facts types as the passed parameters

For example:

public class Methodoveloading    
  {    
    public int sum(int a, int b)  //two int type Parameters method  
    {    
        return a + b;    
            }    
    public int sum(int a, int b,int c)  //three int type Parameters with same method same as above  
    {   
        return a + b+c;    
    }    
    public float sum(float a, float b,float c,float d)  //four float type Parameters with same method same as above two method 
    {    
        return a + b+c+d;    
    
    }    
  }  

Question: What are the control statements which might be utilized in C#?

Answer: You can manage the flow of your set of commands by means of the use of manipulate statements and we majorly focus on if statements. There are a few kinds of if statements that we remember for making situations to manipulate the waft of execution within a program.

These are the four types of if statements:

If

If-else

Nested if

If-else-if 

These statements are generally used within applications.

If statements checks for the person given condition to fulfill their programming condition. If it returns real then the set of commands will be accomplished.

Syntax:

If(any condition)
{
//code to be executed if the condition returns true
}

If-else announcement exams for the given circumstance, if the circumstance turns out to be fake then the waft will transfer to the else assertion and it's going to execute the else instructions. In case, the if condition turns out to be proper then the if commands will get accomplished.

Syntax:

If(condition)
{
//code to be run if the condition is true
}
Else
{
//code to be run if the if-condition is false
}

Nested if statement tests for the circumstance, if the situation is real then it will take a look at for the inner if announcement and maintains going on for the last if statement. If any of the situations are real then it'll execute the unique if instructions and stops the if loop there.

Syntax:

If (condition to be checked)
{
//code
If(condition 2)
{
//code for if-statement 2
}
}

If else-if tests for the given condition, if the situation is not true then the manage will go to the subsequent else condition, if that condition isn't always proper it will maintain on checking for subsequent else conditions. If any of the conditions did not bypass then the closing else commands will get completed.

Syntax:

If(condition 1 to be checked)
{
//code for condition 1
}
Else (condition 2 to be checked)
{
//code for condition 2
}
Else
{
//code will run if no other condition is true
}

Question: Explain the idea of boxing and unboxing of the price kind and item kind in C#.

Answer: 

Boxing- is a procedure of changing a fee kind to an item kind where fee type is positioned at the stack reminiscence, and the item type is positioned inside the heap memory. This conversion is an implicit conversion and you may immediately assign any cost to an object, and C# will take care of the rest of the conversion on its personal.

Example:

public void function()
{
Int a=111;
Object b=a; //implicit conversion
Console.WriteLine(b);
}

Unboxing- it is the reverse process of the boxing method. It is a conversion of the item kind to the cost type and the price of the boxed object kind placed at the heap reminiscence on the way to be transferred to the cost type which is placed at the stack. This conversion of the unboxing process needs to be achieved explicitly.

Example:

public void function()
{
Object b=111;
Int a=(int)b; //implicit conversion
Console.WriteLine(a);
}

Question: How can you take a look at if various is an Armstrong number or now not with C#?

Answer:

using System;  
  public class ArmstrongDemo  
   {  
     public static void Main(string[] args)  
      {  
       int  n,b,sum=0,num;      
       Console.Write("Enter the Number= ");      
       n= int.Parse(Console.ReadLine());     
       num=n;      
       while(n>0)      
       {      
        b=n%10;      
        sum=sum+(b*b*b);      
        n=n/10;      
       }      
       if(num==sum)      
        Console.Write("Armstrong Number.");      
       else      
        Console.Write("Not Armstrong Number.");      
      }  
  }  

Output:

Enter the Number= 371

Armstrong Number.

Question: What is a distinctive method to the passing parameter in C#?

Answer:  Parameters may be passed in 3 one-of-a-kind methods to any defined methods and they may be defined beneath:

Value Parameters:  it'll skip the actual price of the parameter to the formal parameter. In this situation, any changes that are made into the formal parameter of the feature could be having no effect on the real value of the argument.

Reference Parameters: with this method, you may copy the argument that refers back to the reminiscence area into the formal parameter which means any adjustments made to the parameter affect the argument.

Output Parameters: This method returns more than one price to the approach.

Question: What is a multicast delegate in C#?

Answer: A multicast delegate holds the references or addresses to more than one function at a single time. Whenever we invoke the multicast delegate, it's going to invoke all the different features which might be being referred by means of that multicast delegate. You must use the entire approach signature the same as the delegate to call multiple techniques. For example:

namespace MulticastDelegate
{
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.Area(23.45, 67.89);
rect.Perimeter(23.45, 67.89);
Console.ReadKey();
}
}
}

Here, we created an example of the Rectangle elegance and then referred to as the 2 distinctive methods. Now a single delegate will invoke these  methods Area and Perimeter. These described strategies are having the identical signature because the defined delegates that keep the connection with those strategies.

namespace MulticastDelegateDemo
{
public delegate void RectangleDelete(double Width, double Height);
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
RectangleDelete rectDelegate = new RectangleDelete(rect.Area);
rectDelegate += rect.Perimeter;
rectDelegate(23.45, 67.89);
Console.WriteLine();
rectDelegate.Invoke(13.45, 76.89);
Console.WriteLine();
//Removing a method from delegate object
rectDelegate -= rect.Perimeter;
rectDelegate.Invoke(13.45, 76.89);
Console.ReadKey();
}
}
}

Question: How you could enforce nullable<> types in C#? Give an explanation for with the syntax of Nullable kind.

Answer: In C#, you cannot placed a null cost immediately into any variable and the compiler does not guide it. So, the revised version C# 2.Zero presents you with a special function to be able to assign a null cost to a variable this is referred to as as the Nullable type. You can not make the nullable types to paintings with price sorts. Nullable fee can best work with the reference kinds because it already has a null price. System.Nullable<T> shape creates the instance nullable kind, in which T defines the facts kind. This T consists of a non-nullable cost kind that can be any statistics type you want.

Syntax

Nullable<data_type> variable_name=null;

OR

Datatype? variable_name=null;

There is no possibility that you can get admission to the value of the nullable price type at once with assigning the price. For getting its original assigned price you have to use the technique GetValueOrDefault(). If the price is null then it will offer zero as it is its default value.

Question: What do you suggest by using price types and reference types in C#?

Answer:

Value type:

The reminiscence allocated for the price type content material or assigned value is stored on the stack. When we create any variable, space is allotted to that variable and then a price can be assigned to that variable. Also if we want to replicate the cost of that variable to every other variable, its fee receives copied and that creates  distinct variables.

Reference Type:

It holds the reference to the cope with of the object however now not the item at once. Reference sorts represent the deal with of the variable and assigning a reference variable to every other does now not replica the information but it creates a 2d replica of the reference which represents the identical vicinity on the heap as the authentic value. Reference values are saved on the heap and while the reference variable is now not required it gets marked for garbage series.

Question: What are numerous varieties of feedback in C#, explain with example?

Answer:  C# supports 3 sorts of remarks-

1. Single line comment

Syntax:  //single line

2. Multiple line remark

Syntax: /* multiple traces

*/

three. XML comment

Syntax: /// set errors

Question: What are the constructors?

Answer: In C#, there's a special method that is invoked robotically at the time of object advent. It initializes the data members of a brand new object and has the identical call as the class or the shape. There are  forms of constructors:

Default constructor: it has no parameter to bypass.

Parameterized constructor: it's far invoked with parameters which can be handed to the class for the duration of item introduction.

Question: What are the exclusive series classes in C#?

Answer: Collection classes are instructions which might be specially used for records storage and retrieval. These collection instructions will serve many functions like allocating dynamic memory throughout run time and you may even get entry to the items of the gathering the use of the index price that makes the search less complicated and faster. These series lessons belong to the object elegance.

There are many series instructions which can be as follows:

Array listing: it refers back to the ordered series of the objects which are indexed individually. You can use it as an alternative to the array. Using index you could without problems add or put off the gadgets off the list and it will resize itself mechanically. It works well for dynamic reminiscence allocation, including or searching gadgets within the listing.

Hash table: in case you need to access the object of the hash desk then you can use the important thing-fee to consult the original assigned price to the variable. Each item in the hash table is saved as a key/cost pair and the item is referenced with its key cost.

Stack: it works on the concept of final-in and primary-out collection of the items. Whenever you upload an object to the listing it's miles referred to as pushing and while you eliminate the object off the list it's miles called popping.

Sorted list: this series class uses the combination of key and the index to get right of entry to the item in a listing.

Queue: this series works at the concept of first-in and primary-out collection of the object. Adding an object to the list is name enqueue and casting off the object off the listing is call deque.

BitArray: this series class is used to symbolize the array in binary shape (zero and 1). You can use this collection class whilst you do now not realize the range and the items can be accessed by using integer indexes that start from zero.

Question: Explain record handling in C#.

Answer: Whenever you open a report for studying or writing it becomes a flow that's a chain of bytes journeying from source to destination. The  typically used streams are enter and output. The protected namespace is machine.IO that consists of many training for record dealing with. The move is an summary elegance that is the discern elegance for the document handling procedure. The report is a static magnificence with many static strategies to address document operation.

Below are the used training:

The following table describes some commonly used lessons within the System.IO namespace.

Class Name Description
FileStream This stream read from and write to any location within a file
BinaryReader read primitive data types from a binary stream
DirectoryInfo perform operations on directories
FileInfo perform operations on files
BinaryWriter write primitive data types in binary format
StreamReader to read characters from a byte Stream
StreamWriter write characters to a stream.
StringReader read from a string buffer
StringWriter write into a string buffer

Question: Define interface class in C#? Explain with an example.

Answer: An interface magnificence is completely an abstract magnificence that includes abstract techniques and homes. By default, the participants of the interface class are abstract and public with no fields described. If you need to get right of entry to the interface methods then the interface ought to be applied by means of another class the use of ‘:’ image. If you need to define the body of the techniques that could handiest be carried out within the enforcing elegance.

For example:

// Interface
Interface IAnimal {
  void Sound(); // interface method (without body)
}
class Pig : IAnimal   // Pig class "implements" the IAnimal interface
{
  public void Sound()
  {  
Console.WriteLine("The pig says: wee wee"); // The body of Sound() is provided her
  }
}
class Program
{
  static void Main(string[] args)
  {
 Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
  }}

Question: Explain the concept of thread in C#.

Answer: A thread may be defined as the execution glide of any software and defines a unique go with the flow of manage. You can manipulate those threads' execution time in order that their execution does not overlap the execution of other threads and save you impasse or to hold green usage of resources. Threads are light-weight applications that store the CPU intake and boom the performance of the software. The thread cycle starts with the introduction of the item of system.Threading.Thread magnificence and ends when the thread terminates.

System.Threading.Thread class lets in you to handle more than one threads and the first thread usually runs in a procedure known as the main thread. Whenever you run a software in C#, the main thread runs automatically.

Question: Define structure in C# with instance.

Answer: A shape is a data sort of a value type. A struct key-word is used while you're going to outline a structure. A structure represents a report and this record may have many attributes that define the shape.  You can outline a constructor but now not destructor for the shape. You can put into effect one or extra interfaces inside the shape. You can specify a structure but not as summary, digital, or included. If you do no longer use the new operator the fields of the shape continue to be unassigned and you can not use the item till you initialize the fields.

Question: What do you imply by means of user manage and custom manage in C#?

Answer: User controls are very clean to create and are very plenty similar to the ASP manipulate files. You can not region a consumer control at the toolbox and can not even drag-drop it. They have unique design and man or woman code behind those controls. Ascx is the document extension for consumer manage. 

You can create custom code as the compiled code and may be brought to the toolbox. You can encompass these controls to the net bureaucracy without problems. Custom controls may be introduced to more than one packages successfully. If you want to feature a non-public custom manipulate then you may reproduction it to dll and then to the bin listing of your internet software and use its reference there.

Question: C# program to eliminate an element from the queue.

Answer:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application
{
 class DemoProgram
 {
  static void Main(string[] args)
  {
   Queue qs = new Queue();
   qs.Enqueue(1);
   qs.Enqueue(2);
   qs.Enqueue(3);
   foreach (Object ob in qs)
   {
    Console.WriteLine(ob);
   }
    Console.WriteLine(); Console.WriteLine();
    Console.WriteLine("Total number of elements in the Queue " + qs.Count);
    Console.WriteLine("Does the Queue contain " + qs.Contains(3));
    Console.ReadKey();
   }
 }
}

Question: How to discover if a number of is a palindrome or not in C#.

Answer:

using System;  
  public class PalindromeNum  
   {  
     public static void Main(string[] args)  
      {  
          int n,r,num=0,Dem;    
          Console.Write("Enter the Number: ");   
          n = int.Parse(Console.ReadLine());  
          dem=n;      
          while(n>0)      
          {      
           r=n%10;      
           num=(num*10)+r;      
           n=n/10;      
          }      
          if(dem==num)      
           Console.Write("Number is Palindrome.");      
          else      
           Console.Write("Number is not Palindrome");     
    }  
  }  

Question: How will you differentiate among a Class and a Struct?

Answer: Although both class and structure are user-defined data kinds, they're specific in numerous fundamental approaches. A class is a reference kind and shops at the heap. Struct, however, is a cost type and is, consequently, stored on the stack. While the structure doesn’t assist inheritance and polymorphism, the magnificence presents guide for both. A magnificence may be of an summary type, however a shape can’t. All contributors of a category are non-public by means of default, while participants of a struct are public by way of default. Another difference among magnificence and struct is based on reminiscence management. The former supports garbage collection while the latter doesn’t.

Question: Compare Virtual methods and Abstract strategies.

Answer: Any Virtual method ought to have a default implementation, and it could be overridden in the derived magnificence the use of the override keyword. On the contrary, an Abstract approach doesn’t have an implementation, and it is living inside the abstract elegance. The derived magnificence have to put in force the abstract method. Though no longer essential, we will use an override key-word here.

Question: What are Namespaces in C#?

Answer: Use of namespaces is for organizing large code tasks. The most broadly used namespace in C# is System. Namespaces are created using the namespace keyword. It is viable to apply one namespace in some other, referred to as Nested Namespaces.

Question: What are I/O classes in C#? Define a number of the most usually used ones.

Answer: The System.IO namespace in C# includes numerous instructions used for appearing diverse report operations, including introduction, deletion, last, and opening. Some of the maximum often used I/O lessons in C# are:

File – Manipulates a record

Path – Performs operations related to some route facts

StreamReader – Reads characters from a move

StreamWriter – Writes characters to a circulation

StringReader – Reads a string buffer

StringWriter – Writes a string buffer

Question: What do you apprehend by way of normal expressions in C#? Write a software that searches a string the use of regular expressions.

Answer: Regular expression is a template for matching a hard and fast of input. It can encompass constructs, man or woman literals, and operators. Regex is used for string parsing, as well as replacing the person string. Following code searches a string “C#” in opposition to the set of inputs from the languages array using Regex:

static void Main(strong[] args)
{
string[] languages = {“C#”, “Python”, “Java”};
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,“C#”))
{
Console.WriteLine(“Match found”);
}
}
}

Question: Give an in depth explanation of Delegates in C#.

Answer: Delegates are variables that hold references to strategies. It is a feature pointer or reference type. Both the Delegate and the approach to which it refers could have the same signature. All Delegates derives from the

System.Delegate namespace.

Following instance demonstrates affirming a delegate:

public delegate AddNumbers(int n);

After maintaining a delegate, the object ought to be created of the delegate the usage of the new key-word, such as:

AddNumbers an1 = new AddNumbers(number);

The Delegate offers a type of encapsulation to the reference method, which gets internally known as with the calling of the delegate. In the subsequent instance, we've a delegate myDel that takes an integer price as a parameter: public delegate int myDel(int wide variety); public elegance Program  public int AddNumbers(int a)  Int Sum = a + 10; return Sum;  public void Start()  myDel DelgateExample = AddNumbers;  

Question: Explain Reflection in C#.

Answer: The capability of code to access the metadata of the meeting at some stage in runtime is referred to as Reflection. A program displays upon itself and uses the metadata to:

Inform the user, or

Modify the behaviour

The gadget includes all instructions and strategies that manipulate the statistics of all of the loaded types and strategies. Reflection namespace. Implementation of mirrored image is in 2 steps:

Get the type of the item, then

Use the sort to perceive contributors, along with properties and methods

Question: Name some of the maximum common places to look for a Deadlock in C#.

Answer: For spotting deadlocks, one ought to search for threads that get caught on one of the following:

.Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks)

Dispatcher.Invoke() (When running in WPF)

Join() (When operating with Threads)

lock statements (In all cases)

WaitOne() techniques (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore)

Question: Define Serialization and its various kinds in C#.

Answer: The system of changing some code into its binary layout is called Serialization in C#. Doing so lets in the code to be saved effortlessly and written to a disk or a few other garage tool. We use Serialization whilst there is a strict need for no longer dropping the authentic form of the code. A magnificence marked with the characteristic [Serializable] gets converted to its binary shape. A stream that consists of the serialized item and the System.Runtime.Serialization namespace could have lessons for serialization. Serialization in C# is of three sorts:

Binary Serialization – Faster and needs less space; it converts any code into its binary shape. Serialize and repair public and personal houses.

SOAP – It produces a complete SOAP compliant envelope this is usable by using any system able to information SOAP. The training approximately this sort of serialization are living in System.Runtime.Serialization.

XML Serialization – Serializes all of the public houses to the XML document. In addition to being smooth to examine, the XML record manipulated in numerous formats. The instructions in this type of serialization live in System.Sml.Serialization.

Note: Retrieving the C# code again from the binary shape is called Deserialization.

Question: Give a brief clarification of Thread Pooling in C#.

Answer: A series of threads, termed as a Thread Pool in C#. Such threads are for acting responsibilities without disturbing the execution of the primary thread. After a thread belonging to a thread pool completes execution, it returns to the thread pool. Classes that manipulate the thread inside the thread pool, and its operations, are contained within the System.Threading.ThreadPool namespace.

Question: Is it viable to use this keyword inside a static approach in C#?

Answer: A special form of reference variable, this key-word is implicitly defined with each non-static approach and constructor as the first parameter of the sort class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist with out creating an example of the class and calls with the name of the elegance. Because this key-word returns a connection with the present day example of the elegance containing it, it may’t be utilized in a static technique. Although we will’t use this key-word within a static technique, we can use it within the feature parameters of Extension Methods.

Question: What are you able to tell us about the XSD report in C#?

Answer: XSD denotes XML Schema Definition. The XML report will have any attributes, factors, and tags if there's no XSD record related to it. The XSD report gives a shape for the XML file, meaning that it determines what, and also the order of, the factors and houses that need to be there inside the XML document. Note: - During serialization of C# code, the lessons are converted to XSD compliant format by means of the Xsd.Exe tool.

Question: What do you suggest through Constructor Chaining in C#?

Answer: Constructor chaining in C# is a way of connecting  or extra lessons in a relationship as an inheritance. Every infant elegance constructor is mapped to the discern elegance constructor implicitly via the use of the bottom key-word in constructor chaining.

Question: Explain one of a kind states of a Thread in C#?

Answer: A thread in C# will have any of the following states:

Aborted – The thread is lifeless however not stopped

Running – The thread is executing

Stopped – The thread has stopped execution

Suspended – The thread has been suspended

Unstarted – The thread is created but has not started execution but

WaitSleepJoin – The thread calls sleep, calls wait on some other object, and calls join on some different thread

Question: Why will we use Async and Await in C#?

Answer: Processes belonging to asynchronous programming run independently of the primary or different processes. In C#, the usage of Async and Await key phrases for developing asynchronous strategies.

Question: What is an Indexer in C#, and the way do you create one?

Answer: Also known as an indexed property, an indexer is a category assets allowing having access to a member variable of a few magnificence using functions of an array. Used for treating an item as an array, indexer allows the use of training more intuitively. Although now not an crucial part of the object-orientated programming, indexers are a clever way of using arrays. As such, they're additionally referred to as clever arrays. Defining an indexer enables creating instructions that act like digital arrays. Instances of such instructions may be accessed using the [] array access operator. The wellknown syntax for creating an indexer in C# is:

< modifier > <
return type > this[argument list] {
get {
// the get block code
}
set {
// the set block code
}
}

Question: What is the Race circumstance in C#?

Answer: When two threads access the equal resource and try to change it at the same time, we've a race circumstance. It is nearly impossible to expect which thread succeeds in having access to the resource first. When  threads try to write a value to the equal resource, the remaining price written is saved.

Question: What do you recognize with the aid of Get and Set Accessor homes?

Answer: Made the usage of houses, Get and Set are referred to as accessors in C#. A assets allows studying and writing to the fee of a personal subject. Accessors are used for gaining access to such private fields. While we use the Get property for returning the price of a belongings, use the Set assets for setting the fee.

Question: Give a detailed clarification of the variations among ref and out keywords.

Answer: In any C# function, there may be three sorts of parameters, namely in, out and ref. Although both out and ref are dealt with in another way at the run time, they acquire the equal remedy during the collect time. It is not viable to pass homes as an out or ref parameter. Following are the variations between ref and out keywords:

Initializing the Argument or Parameter – While it isn't always obligatory to initialize an argument or parameter before passing to an out parameter, the identical wishes to be initialized earlier than passing it to the ref parameter.

Initializing the Value of the Parameter – Using ref doesn’t necessitate for assigning or initializing the value of a parameter before returning to the calling technique. When the usage of out, however, it is obligatory to use a known as technique for assigning or initializing a fee of a parameter earlier than returning to the calling method.

Usefulness – When the called method calls for enhancing the exceeded parameter, passing a parameter cost through Ref is beneficial. Declaring a parameter to an out technique is suitable when a couple of values are required to be back from a feature or method.

Initializing a Parameter Value in Calling Method – It is a compulsion to initialize a parameter price in the calling approach even as the usage of out. However, the same is non-compulsory whilst the usage of the ref parameter.

Data Passing – Using out allows for passing facts only in a unidirectional way. However, records may be handed in a bidirectional manner whilst the usage of ref.

Question: What is Singleton Design Patterns in C#? Explain their implementation the usage of an instance.

Answer: A singleton in C# is a category that lets in the creation of handiest a unmarried example of itself and provides simple get right of entry to to that sole example. Because the second one request of an instance with a unique parameter can reason troubles, singletons generally disallow any parameters to be exact. Following instance demonstrates the implementation of Singleton Design Patterns in C#:

namespace Singleton {
class Program {
static void Main(string[] args) {
Calculate.Instance.ValueOne = 10.5;
Calculate.Instance.ValueTwo = 5.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.WriteLine("\n----------------------\n");
Calculate.Instance.ValueTwo = 10.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.ReadLine();
}
}
public sealed class Calculate {
private Calculate() {}
private static Calculate instance = null;
public static Calculate Instance {
get {
if (instance == null) {
instance = new Calculate();
}
return instance;
}
}
public double ValueOne {
get;
set;
}
public double ValueTwo {
get;
set;
}
public double Addition() {
return ValueOne + ValueTwo;
}
public double Subtraction() {
return ValueOne - ValueTwo;
}
public double Multiplication() {
return ValueOne * ValueTwo;
}
public double Division() {
return ValueOne / ValueTwo;
}
}
}

A Singleton Design Pattern guarantees that a class has one and only one instance and gives a worldwide factor of get right of entry to to the same. There are numerous methods of implementing the Singleton Design Patterns in C#. Following are the typical characteristics of a Singleton Pattern:

A public static method of having the reference to the single example created

A unmarried constructor, private and parameter-less

A static variable protecting a connection with the single example created

The magnificence is sealed

Conclusion

That sums up the listing of the top c# interview questions for skilled experts and beginners as properly. How some of the answers did  already? Let us realize via remarks. Check out those nice C# tutorials to decorate your C# knowledge in addition.

Looking for greater C# coding issues interview questions? We recommend one of the quality C# interview publications: C# Advanced Topics: Prepare for Technical Interviews.




CFG