c# interview questions for experienced

Table of Contents

Introduction to c# interview questions for experienced

The following are the most commonly asked questions in C# interviews for the C# developers planning to enter an interview. Below, I listed some of the best interview questions for C# and .net. These C# Interview Questions are designed to help experienced professional developers in the C# language. The post title is c# interview questions for experienced but the juniors and mid-level developers can check to have more in-depth experience.

What is C#?

C# “C-Sharp” is an object-oriented programming language created by Microsoft that runs on the .NET Framework.

Tell me the use of delegates in C#?

A delegate is a type that represents references to methods with a particular parameter list and return type. A delegate in C# is similar to a function pointer in C or C++. A delegate is a type that represents a method signature along with an object instance. A delegate is like an interface with a single method of a given signature, declared using the delegate keyword. The purpose of using delegates is to expose certain operations as entities (methods) so we can pass them as arguments, return them as results, or store them separately from other code while maintaining the ability to call them when needed.

namespace DelegateApplication;

delegate int NumberChanger(int n);

class TestDelegate
{
    static int number = 10;
    public static int AddNum(int p)
    {
        number += p;
        return number;
    }
    public static int MultiplyNumber(int q)
    {
        number *= q;
        return number;
    }
    public static int getNumber()
    {
        return number;
    }
    static void Main(string[] args)
    {
        //create delegate instances
        NumberChanger numberChanger1 = new(AddNum);
        NumberChanger numberChanger2 = new(MultiplyNumber);
        //calling the methods using the delegate objects
        numberChanger1(25);
        Console.WriteLine("Value of Number: {0}", getNumber());
        numberChanger2(5);
        Console.WriteLine("Value of Number: {0}", getNumber());
        Console.ReadKey();
    }
}

 

What is an object in C#?

An object is a meaning (instance) of some type. We create objects using constructors, and we use methods to operate on them. An instance of a class that stores names and addresses, for example, might include several properties such as Initials, name, date of birth, address, and more. On other words, the object is a chunk of memory that contains both data and methods.

What are the class and what are the types of classes in C#?

Class is a container for data and code. We group related data and methods into classes so we don’t have to write duplicated code every time we need the same functionality.

There are some types of classes in c# as

  • Abstract
  • Partial
  • Sealed
  • Static                                                                          

What is enum in C#?

The name of enum is short for enumeration. Enum defines a type that is used to store values ​​of a certain set. It’s a convenient way to express a group of related values as a single entity. It’s also a powerful way to group related functionality together in your application.

enum CustomerStatus
{
    New=1,
    Registered,
    Paused,
    Blocked,
    Removed
}

 

What is a managed and unmanaged code, and what are the differences between the both?

Manged code:

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

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.

What is Common Language Runtime (CLR)?

The common language runtime (CLR) is an execution environment and a set of services that support the execution of “managed” code, which executes within the context of a Common Language Infrastructure (CLI). The Common Language Runtime (CLR) is a shared environment in which applications execute. It provides services such as memory management and exception handling that are necessary for executing managed code. The Common Language Runtime (CLR) is a central feature of the .NET Framework and its task is to manage the execution of programs written in any language supported by the framework. It is analogous to the operating system kernel in that it uses many available parts of the underlying operating system to provide platform independence for managed applications.

What is the difference between read-only and constant in C#?

Constant should be instantiated when defined, should take a value, and read-only can be defined without taking a value

What are the differences between ref and out keywords?

  ref vs out

Tell me the difference between finalize and dispose methods in C#?

Finalize is called implicitly and it is called by the garbage collector which means it can’t be called manually by the developer. On the other hand, dispose is called explicit which means dispose is called manually by the developer. both finalize and dispose are used to free the unmanaged (idle or not used) resources such as database connections, files, variables, etc.

Difference Between Static Class, Sealed Class, and Abstract Class in C#

We come across this question very often what is the difference between Static, Sealed, and Abstract classes in C#.

Static Class: Declared with Static keyword, methods in Static Class are also static along with variables of the class. This class cannot be instantiated, i.e we cannot have objects of this class. To access the methods of this class, you can directly use the class name. method. Also, this class cannot be inherited.

Sealed Class: Declared with the Sealed keyword, which enables this class to seal all its variables, methods, and properties. No other class can inherit anything from this class in other words, this class cannot be inherited. But we can instantiate this class, i.e we can have any number of objects of a sealed class.

Abstract Class: Declared with abstract keyword, this class is primarily created as an Inheritable class. An abstract class enables other classes to inherit from this class but forbids instantiation. One can inherit from an abstract class but we cannot create objects of an abstract class. An abstract class can have abstract as well as non-abstract methods. Abstract methods are those which do not have a method definition.

One important point to remember is a non-static class can have static methods. But Static classes must have all members as Static.

Tell me the difference between interface and abstract class in C#?

The big difference between interface and abstract class is that abstract class can have implementation inside it but interfaces can have only signatures. 

  • Abstract classes are classes that cannot be instantiated ie. that cannot create an object. The interface is like an abstract class because all the methods inside the interface are abstract methods.
  • Abstract classes can have both abstract and non-abstract methods but all the methods of an interface are abstract methods.
  • Since abstract classes can have both abstract and non-abstract methods, we need to use the Abstract keyword to declare abstract methods. But in the interface, there is no such need.
  • An abstract class has constructors while an interface encompasses none. 

Tell me the difference between “continue” and “break” statements in C#?

Using the keyword break, the loop will exit but the continue keyword will just jump or skip on the iteration of the loop

What are properties in C#?

Generally, in programming, a property is a feature of an object or class that provides access to the “underlying” data.

What is the extension method in C#?

Extension methods, as the name suggests, are additional methods. Extension methods allow you to inject additional methods without modifying, deriving, or recompiling the original class, struct, or interface. Extension methods can be added to your own custom class, .NET framework classes, or third-party classes or interfaces.

namespace ExtensionMethodApplication;

public class CustomClass
{
    public string FundMe()
    {
        return ("I'm in Fund");
    }

    public string DisplayMe()
    {
        return ("I'm in Display");
    }

    public string PrintMe()
    {
        return ("I'm in Print");
    }
}

public static class MyExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(new char[] { ' ', '.', '?' },
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }

    public static void NewMethod(this CustomClass customClass)
    {
        Console.WriteLine("Hello I'm extended method for CustomClass");
    }
}

class program
{
    static void Main(string[] args)
    {
        // Extension method for built in string
        string s = "Hello Extension Methods";
        int i = s.WordCount();

        // Extension method for custom class
        CustomClass customClass=new();
        customClass.NewMethod();

    }
}

  c# extension methods

What are the IEnumerable and IQueryable what are the differences between both?

Both IEnumerable and IQueryable will give you deferred execution. Both are used in getting data from a collection, iterating, and manipulating items inside the collected data collection.
The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.
For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.

What is the partial class in C#?

A partial class allows you split the definition of a class over multiple files. There are several reasons you might want to do this. One reason is to separate the implementation of a set of properties from their declaration in the class declaration. Another reason is to split interface from implementation when differentiating between .NET and native code, or to reduce compile-time dependencies between projects.

What is the Indexer in C#?

The smart array or Indexers are methods that allow a class to be used as an associative array. In other words, an indexer allows you to use instances of the class as if they were arrays. The Indexer class, or indexer for short, acts like a property. It gives you access to the underlying field of an object without the need to know its type. Indexers are the implementation for reading and writing hash codes.

namespace Challenges;

class StringStore
{
    private string[] stringArray = new string[100]; 

    public string this[int index]
    {
        get
        {
            if (index < 0 || index >= stringArray.Length)
                throw new IndexOutOfRangeException("Index out of range");

            return stringArray[index];
        }

        set
        {
            if (index < 0 || index >= stringArray.Length)
                throw new IndexOutOfRangeException("Index out of range");

            stringArray[index] = value;
        }
    }
}

class Program
{
    static void main()
    {
        StringStore stringStore = new();

        for (int i = 0; i < 100; i++)
        {
            stringStore[i] = i.ToString();
        }

        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(stringStore[i]);
        }
    }
}

 

Tell me the difference between boxing and unboxing in C#?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

int i = 123;
// The following line boxes i.
object o = i;

o = 123;
i = (int)o; // unboxing

 

Tell me the difference between class and struct in C#?

Class:

  •  A class is a reference type.
  •  While instantiating a class, CLR allocates memory for its instance in heap.
  • Classes support inheritance.
  • Variables of a class can be assigned as null.
  • Classes can contain a constructor/destructor.

Structure:

  • A structure is a value type.
  • In structure, memory is allocated on the stack.
  • Structures do not support inheritance.
  • Structure members cannot have null values.
  • Structure does not require a constructor/destructor and members can be initialized automatically.

Can “this” be used in a static method?

No, You can’t use this within a static method as the “this” keyword is used to reference/refer to an instance.

What are sealed classes in C#?

Sealed class is the class that can’t be inherited

What are the differences between String and StringBuilder in C#?

StringBuilder is more efficient than string.

String:- It is Immutable and resides within System Namespace.

StringBuilder:-It is mutable and resides System.Text Namespace.

Tell me the difference between late binding and early binding in C#?

Late Binding or Overriding is a type of polymorphism when you change the method logic

Early Binding or Overloading is another type of polymorphism. Methods can be overloaded with the help of various types of data for a parameter, several orders of parameters, and a varied number of parameters 

What are the generics in C#?

Generics means a global or general form, not a specific form. It allows you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. The below code snippet shows an example of a generic repository pattern

using System.Linq.Expressions;

namespace Infrastructure;

public class Repository<T> : IRepository<T> where T : class, IBaseEntity
{
    protected DbContext dbContext;
    protected DbSet<T> store;
  
    public Repository()
    {
        store = dbContext.Set<T>();
    }

    public virtual IQueryable<T> Get(Expression<Func<T, bool>> where)
    {
        var query = store.Where(where);
        return query;
    }

    public virtual T Add(T item)
    {
        return store.Add(item).Entity;
    }

    public virtual T Update(T item)
    {
        store.Attach(item);
        dbContext.Entry(item).State = EntityState.Modified;
        return item;
    }

    public virtual void Delete(Expression<Func<T, bool>> where)
    {
        T item = store.Where(where).FirstOrDefault();
        if (item != null)
        {
            store.Remove(item);
            dbContext.Entry(item).State = EntityState.Deleted;
        }
    }

    public virtual bool SoftDelete(Expression<Func<T, bool>> where)
    {
        T item = store.Where(where).FirstOrDefault();
        if (item != null)
        {
            item.IsDeleted = true;
            dbContext.Entry(item).State = EntityState.Modified;
            return true;
        }
        return false;
    }
   
    public virtual bool ExecuteTransaction(Action transactionBody)
    {
        using (var trans = dbContext.Database.BeginTransaction())
        {
            try
            {
                transactionBody.Invoke();
                trans.Commit();
                return true;
            }
            catch (System.Exception ex)
            {
                trans.Rollback();
                return false;
            }
        }
    }

}

 

Tell me the difference between the equality operator (==) and equals() method in C#?

The == Operator compares the reference identity while the Equals() method compares only contents.

Tell me the different ways a method can be Overloaded in C#?

Method overloading can be done by changing:

  1. The number of parameters in two methods.
  2. The data types of the parameters of methods.
  3. The Order of the parameters of methods.

What is garbage collection in C#?

Garbage collection, or GC for short, is a programming model that automatically manages memory for the programmer. Garbage collection is voodoo magic performed by .NET and .NET Compact Framework runtime when you don’t explicitly free all memory after usage. You don’t need to worry about it most of the time though. The garbage collector does everything for you in a way that you cannot even really notice it.

Tell me the meaning of inheritance? Does C# support multiple inheritance?

Inheritance means driving data, structure, logic, etc from the base class or entity to the child or drived classes or entities.

c# doesn’t support multiple inheritance.

Explain different types of inheritance.

Inheritance in OOP is of four types:

  • Single inheritance – Contains one base class and one derived class
  • Hierarchical inheritance – Contains one base class and multiple derived classes of the same base class
  • Multilevel inheritance – Contains a class derived from a derived class
  •  Multiple inheritance – Contains several base classes and a derived class

All .NET languages support single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because, in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces.

What is the process of .NET code compilation/execution?

  1. The code is written in one of the high-level languages in .NET, such as C#, VB.NET, and others
  2. You compile the code to get the Intermediate Language code (IL)
  3. When you execute the code, the CLR runs the IL code
  4. The CLR converts the IL code to machine code that can run on the CPU

What is the .net grandfather class?

The System.Object class is the parent class of all .net classes, it contains some basic functions such as Equals(), ToString(), etc

Conclusion

The experienced and professional c# developer interview level is absolutely different from beginner and it is expected that the level of interview for experienced developers will be tough and harder compared to the junior developers. In this post for c# interview questions for experienced, I put some of the most common interview questions and their answers for experienced c# developers.

You can find source code samples at github Enjoy…!!! I can help you to build such as software tools/snippets, you contact me from here

Leave a Reply

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