FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

39+ Advanced C# Interview Questions (ANSWERED) .NET Must Know

Having a Senior Developer C# Interview? Don't panic, we got you covered! Check that list of 39 top most advanced C# interview questions for experienced developer and got your next six-figure job offer in style!

Q1: 
What is an Object?

Answer

According to MSDN, "a class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically".

Objects helps us to access the member of a class or struct either they can be fields, methods or properties, by using the dot.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q2: 
What is the difference between continue and break statements in C#?

Answer
  • using break statement, you can jump out of a loop
  • using continue statement, you can jump over one iteration and then resume your loop execution


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q3: 
How is Exception Handling implemented in C#?

Answer

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.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q4: 
What are dynamic type variables in C#?

Answer

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q5: 
What is Boxing and Unboxing?

Answer

Boxing and Unboxing both are used for type conversion but have some difference:

  • Boxing - Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.

  • Unboxing - Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.

The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q6: 
What is Managed or Unmanaged Code?

Answer
  • Managed Code - The code, which is developed in .NET framework is known as managed code. This code is directly executed by CLR with the help of managed code execution. Any language that is written in .NET Framework is managed code.
  • Unmanaged Code - The code, which is developed outside .NET framework is known as unmanaged code. Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with the code of VB, ASP and COM are examples of unmanaged code.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q7: 
What is namespace in C#?

Answer

A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.

  • NET uses namespaces to organize its many classes.
  • Declaring your own namespaces can help you control the scope of class and method names in larger programming projects.
namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
              "SampleMethod inside SampleNamespace");
        }
    }
}

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q8: 
What is the difference between a Struct and a Class in C#?

Answer

Class and struct both are the user defined data type but have some major difference:

Struct

  • The struct is value type in C# and it inherits from System.Value Type.
  • Struct is usually used for smaller amounts of data.
  • Struct can't be inherited to other type.
  • A structure can't be abstract.

Class

  • The class is reference type in C# and it inherits from the System.Object Type.
  • Classes are usually used for large amounts of data.
  • Classes can be inherited to other class.
  • A class can be abstract type.
  • We can create a default constructor.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
Why to use finally block in C#?

Answer

Finally block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last finally block will be executed. So closing connection to database / releasing the file handlers can be kept in finally block.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q10: 
Can you return multiple values from a function in C#? Provide some examples.

Answer

There are several ways.

Use ref / out parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function.

Consider:

private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
    add = a + b;
    multiply = a * b;
}

or

private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
    add = a + b;
    multiply = a * b;
}

Another way is to use <Tuple>:

private static Tuple<int, int> Add_Multiply(int a, int b)
{
    var tuple = new Tuple<int, int>(a + b, a * b);
    return tuple;
}

Now that C# 7 has been released, you can use the new included Tuples syntax:

(string, string, string) LookupName(long id) // tuple return type
{
    ... // retrieve first, middle and last from data storage
    return (first, middle, last); // tuple literal
}

which could then be used like this:

var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q11: 
Explain Anonymous type in C#

Answer

Anonymous types allow us to create a new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.

Consider:

var anonymousData = new
{  
     ForeName = "Jignesh",  
     SurName = "Trivedi"
};  

Console.WriteLine("First Name : " + anonymousData.ForeName); 

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q12: 
Explain the difference between Task and Thread in .NET

Answer
  • Thread represents an actual OS-level thread, with its own stack and kernel resources. Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread, you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture. ThreadPool is a wrapper around a pool of threads maintained by the CLR.

  • The Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool. Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result.


Having Tech or Coding Interview? Check 👉 68 .NET Core Interview Questions

Q13: 
How encapsulation is implemented in C#?

Answer

Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member.

  • Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
  • Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
  • Protected access specifier allows a child class to access the member variables and member functions of its base class. This way it helps in implementing inheritance.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q14: 
Refactor the code

Problem
class ClassA
{
  public ClassA() { }

  public ClassA(int pValue) {  }
}

// client program
class Program
{
  static void Main(string[] args)
  {
    ClassA refA = new ClassA();
  }
}

Is there a way to modify ClassA so that you can you call the constructor with parameters, when the Main method is called, without creating any other new instances of the ClassA?

Answer

The this keyword is used to call other constructors, to initialize the class object. The following shows the implementation:

class ClassA
{
  public ClassA() : this(10)
  { }

  public ClassA(int pValue)
  {  }
}

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions
Source: toptal.com

Q15: 
What are the uses of using in C#

Answer

The reason for the using statement is to ensure that the object is disposed (call IDisposable) as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

The .NET CLR converts:

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

to:

{ // Limits scope of myRes
    MyResource myRes= new MyResource();
    try
    {
        myRes.DoSomething();
    }
    finally
    {
        // Check for a null resource.
        if (myRes != null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();
    }
}

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
What is lambda expressions in C#?

Answer

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

In the following example, the lambda expression x => x * x, which specifies a parameter that's named x and returns the value of x squared, is assigned to a variable of a delegate type:

Func<int, int> square = x => x * x;
Console.WriteLine(square(5));
// Output:
// 25

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q17: 
What is a Destructor in C# and when shall I create one?

Answer

A Destructor is used to clean up the memory and free the resources. But in C# this is done by the garbage collector on its own. System.GC.Collect() is called internally for cleaning up. The answer to second question is "almost never".

Typically one only creates a destructor when your class is holding on to some expensive unmanaged resource that must be cleaned up when the object goes away. It is better to use the disposable pattern to ensure that the resource is cleaned up. A destructor is then essentially an assurance that if the consumer of your object forgets to dispose it, the resource still gets cleaned up eventually.

If you make a destructor be extremely careful and understand how the garbage collector works. Destructors are really weird:

  • They don't run on your thread; they run on their own thread. Don't cause deadlocks!
  • An unhandled exception thrown from a destructor is bad news. It's on its own thread; who is going to catch it?
  • A destructor may be called on an object after the constructor starts but before the constructor finishes. A properly written destructor will not rely on invariants established in the constructor.
  • A destructor can "resurrect" an object, making a dead object alive again. That's really weird. Don't do it.
  • A destructor might never run; you can't rely on the object ever being scheduled for finalization. It probably will be, but that's not a guarantee.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q18: 
What is difference between constant and readonly?

Answer

A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a const is always constant but readonly is read-only once it is assigned.

When to use const or readonly:

  • const

    • compile-time constant: absolute constant, value is set during declaration, is in the IL code itself
  • readonly

    • run-time constant: can be set in the constructor/init via config file i.e. App.config, but once it initializes it can't be changed

Consider a class defined in AssemblyA.

public class Const_V_Readonly
{
  public const int I_CONST_VALUE = 2;
  public readonly int I_RO_VALUE;
  public Const_V_Readonly()
  {
     I_RO_VALUE = 3;
  }
}

AssemblyB references AssemblyA and uses these values in code. When this is compiled,

  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if tomorrow I'll update I_CONST_VALUE to 20 in the future. AssemblyB would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

Remember: If you reference a constant from another assembly, its value will be compiled right into the calling assembly. That way when you update the constant in the referenced assembly it won't change in the calling assembly!


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q19: 
What is the difference between Interface and Abstract Class?

Answer

There are some differences between Abstract Class and Interface which are listed below:

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

Consider using abstract classes if :

  1. You want to share code among several closely related classes.
  2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
  3. You want to declare non-static or non-final fields.

Consider using interfaces if :

  1. You expect that unrelated classes would implement your interface. For example, many unrelated objects can implement Serializable interface.
  2. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
  3. You want to take advantage of multiple inheritances of type.

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q20: 
What is the difference between overloading and overriding?

Answer
  • Overloading is when you have multiple methods in the same scope, with the same name but different signatures.
//Overloading
public class test
{
    public void getStuff(int id)
    {}
    public void getStuff(string name)
    {}
}
  • Overriding is a principle that allows you to change the functionality of a method in a child class.
//Overriding
public class test
{
        public virtual void getStuff(int id)
        {
            //Get stuff default location
        }
}

public class test2 : test
{
        public override void getStuff(int id)
        {
            //base.getStuff(id);
            //or - Get stuff new location
        }
}

Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q21: 
What is the difference between ref and out keywords?

Answer
  • ref tells the compiler that the object is initialized before entering the function, while
  • out tells the compiler that the object will be initialized inside the function.

So while ref is two-ways, out is out-only.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions

Q22: 
What is the output of the program below? Explain.

Problem

Consider:

delegate void Printer();

static void Main()
{
        List<Printer> printers = new List<Printer>();
        int i=0;
        for(; i < 10; i++)
        {
            printers.Add(delegate { Console.WriteLine(i); });
        }

        foreach (var printer in printers)
        {
            printer();
        }
}
Answer

This program will output the number 10 ten times.

Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions
Source: toptal.com
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
Why can't you specify the accessibility modifier for methods inside the Interface?

Answer

In an interface, we have virtual methods that do not have method definition. All the methods are there to be overridden in the derived class. That's why they all are public.


Having Tech or Coding Interview? Check 👉 127 C# Interview Questions
Source: guru99.com

Q24: 
Explain how does Asynchronous tasks Async/Await work in .NET?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q25: 
What are pointer types in C#?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q26: 
What interface should your data structure implement to make the Where method work?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q27: 
What is Marshalling and why do we need it?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q28: 
What is difference between late binding and early binding in C#?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q29: 
What is the yield keyword used for in C#?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q30: 
What is the difference between Func<string,string> and delegate?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q31: 
What is the output of the program below?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q32: 
What is the output of the program below? Explain your answer.

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q33: 
What is the output of the short program below? Explain your answer.

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q34: 
What is the use of conditional preprocessor directive in C#?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q35: 
Why to use lock statement in C#?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q36: 
Implement the Where method in C#. Explain.

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q37: 
What are the benefits of a Deferred Execution in LINQ?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q38: 
What is jagged array in C# and when to prefer jagged arrays over multi-dimensional arrays?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q39: 
What is a preprocessor directives in C#?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...