Interview question and answers

OOPS, or Object-Oriented Programming System, is a programming paradigm that organizes software design around objects rather than functions or logic. An object is an instance of a class, which can contain data (attributes or properties) and methods (functions or behaviors) that operate on the data.OOP concepts help organize and structure code for better reusability, scalability, and maintenance.

Here are the core OOP concepts in C#:

1. Encapsulation

  • Encapsulation is the process of keeping data and methods that operate on that data within a single unit (i.e., a class) and restricting direct access to some of the object's components.
  • This is achieved in C# by defining access modifiers like public, private, and protected.
  • Example:
    csharp
    public class Car { private int speed; // Private field - accessible only within the class public int Speed // Public property with getter and setter { get { return speed; } set { speed = value > 0 ? value : 0; } } }

2. Abstraction

  • Abstraction is the concept of hiding complex implementation details and showing only the necessary features of an object.
  • This is often achieved using abstract classes and interfaces in C#.
  • Example:
    csharp
    public abstract class Shape { public abstract double GetArea(); } public class Circle : Shape { public double Radius { get; set; } public override double GetArea() { return Math.PI * Radius * Radius; } }

3. Inheritance

  • Inheritance allows a class to inherit members (fields, properties, and methods) from another class, promoting code reuse.
  • In C#, a class can inherit from a single base class.
  • Example:
    csharp
    public class Vehicle { public string Color { get; set; } public void Start() => Console.WriteLine("Vehicle started."); } public class Car : Vehicle { public void Drive() => Console.WriteLine("Car is driving."); }

4. Polymorphism

  • Polymorphism allows methods to do different things based on the object it is acting upon, even if the method is defined with the same name.
  • Polymorphism in C# can be achieved via method overriding and interfaces.
  • Example:
    csharp
    public class Animal { public virtual void Speak() { Console.WriteLine("Animal sound."); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Woof!"); } } public class Cat : Animal { public override void Speak() { Console.WriteLine("Meow!"); } }

In C#, these are access modifiers that control the visibility or accessibility of classes and members (like fields, methods, properties) in your code. Each modifier defines where a class or member can be accessed from. Here's a breakdown:

1. public

  • Definition: The public access modifier allows members to be accessed from anywhere in the application.
  • Usage: Classes, properties, and methods marked as public are accessible from other classes, namespaces, and assemblies.
  • Example:
    csharp
    public class Car { public string Model; // Accessible from any code in the project }

2. private

  • Definition: The private access modifier restricts access to the containing class only. No other classes, even derived ones, can access private members.
  • Usage: Commonly used to hide sensitive data or implementation details that should not be accessible outside the class.
  • Example:
    csharp
    public class Car { private string color; // Only accessible within the Car class }

3. protected

  • Definition: The protected access modifier allows access within the containing class and any derived classes.
  • Usage: Useful for members that should be visible to subclasses but hidden from other classes.
  • Example:
    csharp
    public class Vehicle { protected string brand; // Accessible in Vehicle and derived classes } public class Car : Vehicle { public void ShowBrand() { Console.WriteLine(brand); // Accessible in the Car class (derived from Vehicle) } }

4. internal

  • Definition: The internal access modifier restricts access to within the same assembly (project).
  • Usage: Useful for classes or members that are intended to be used only within the same project but not from external projects.
  • Example:
    csharp
    internal class Engine { // Accessible only within the same assembly }

5. protected internal

  • Definition: The protected internal access modifier combines protected and internal. It allows access from derived classes and any class within the same assembly.
  • Usage: This access level is useful when you want to expose members to both derived classes and other classes within the same assembly.
  • Example:
    csharp
    public class Vehicle { protected internal int speed; // Accessible within derived classes or the same assembly }

6. private protected (C# 7.2 and later)

  • Definition: The private protected access modifier restricts access to the containing class or derived classes within the same assembly.
  • Usage: Useful when you want members to be accessible in derived classes, but only if they are in the same project.
  • Example:
    csharp
    public class Vehicle { private protected int fuelLevel; // Accessible in derived classes within the same assembly only }

Summary Table:

ModifierAccessible within the ClassAccessible in Derived ClassesAccessible within the Same AssemblyAccessible Outside the Assembly
publicYesYesYesYes
privateYesNoNoNo
protectedYesYesNoNo
internalYesNoYesNo
protected internalYesYesYesNo
private protectedYesYesOnly within the same assemblyNo

These access modifiers help to enforce encapsulation by controlling where classes and members can be accessed.


In C#, the static keyword is used to define members (variables, methods, properties) or classes that belong to the type itself rather than to an instance of the type. This means that static members are shared across all instances of a class, and you do not need to create an object of the class to access them.

Here’s a closer look at what static means and how it’s used:

1. Static Fields and Methods

  • Static Field: A static field is a variable that belongs to the class itself, not to any specific instance. All instances of the class share the same static field, so changing its value in one instance affects it for all instances.
  • Static Method: A static method can be called on the class itself, without creating an instance. It can only access other static members (fields, properties, etc.) directly.
csharp
public class Calculator { public static int counter = 0; // Shared by all Calculator objects public static int Add(int a, int b) { return a + b; } } // Usage: int result = Calculator.Add(5, 10); // Calls static method directly on the class Console.WriteLine(Calculator.counter); // Accesses static field directly on the class

2. Static Classes

  • A static class can only contain static members and cannot be instantiated. It’s useful for grouping utility methods together, such as a Math class with mathematical functions.
  • Static classes are sealed by default (cannot be inherited) and serve as containers for related static members.
csharp
public static class MathUtilities { public static double Pi = 3.14159; public static double Square(double number) { return number * number; } } // Usage: double result = MathUtilities.Square(5); // Calls static method on static class

3. Static Constructors

  • A static constructor is used to initialize static fields or perform actions once per type, not per instance. It runs automatically before the first use of any static member in a class.
  • A class can only have one static constructor, which has no parameters and cannot be called directly.
csharp
public class Configuration { public static string Setting; static Configuration() // Static constructor { Setting = "Default setting"; } }

When to Use static:

  • Use static for members that are shared across all instances of a class and do not depend on instance-specific data.
  • Use static classes when you only need utility functions or constants that do not require an object instance (e.g., helper functions or configuration values).

Summary:

  • static makes a member or class belong to the type itself, rather than to instances of the type.
  • Static members are accessed directly through the class name.
  • A static class cannot be instantiated and can only contain static members.

Ref and Const difference :


Feature

ref

const

Purpose

Passes a variable by reference

Declares a fixed, unchangeable value

Modifiable

Yes, allows modification

No, value cannot be changed after declaration

Initialization

Must be initialized before use

Must be initialized at the time of declaration

Scope of Change

Changes persist outside the method

Remains constant throughout the program

Usage in Methods

Used for method parameters

Cannot be used as a parameter

Compile-Time

Not evaluated at compile time

Value known and fixed at compile time

Data Type

Can be any variable type

Limited to primitive types and enums

Use Case

When you need a method to modify input

For values that should remain constant




C# | Constructors

A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. 

Example :  

class Geek
{   
  .......
  // Constructor
  public Geek() {}
  .......
}

// an object is created of Geek class,
// So above constructor is called
Geek obj = new Geek(); 

Important points to Remember About Constructors

  • Constructor of a class must have the same name as the class name in which it resides.
  • A constructor can not be abstract, final, and Synchronized.
  • Within a class, you can create only one static constructor.
  • A constructor doesn’t have any return type, not even void.
  • A static constructor cannot be a parameterized constructor.
  • A class can have any number of constructors.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor. 
     

Types of Constructor

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Private Constructor
  5. Static Constructor

Default Constructor

A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.

Example : 

// C# Program to illustrate calling
// a Default constructor
using System;
namespace DefaultConstructorExample {
 
class Geek {
 
    int num;
    string name;
 
    // this would be invoked while the
    // object of that class created.
    Geek()
    {
        Console.WriteLine("Constructor Called");
    }
 
    // Main Method
    public static void Main()
    {
 
        // this would invoke default
        // constructor.
        Geek geek1 = new Geek();
 
        // Default constructor provides
        // the default values to the
        // int and object as 0, null
        // Note:
        // It Give Warning because
        // Fields are not assign
        Console.WriteLine(geek1.name);
        Console.WriteLine(geek1.num);
    }
}
}


Output : 

Constructor Called

0


Note : This will also show some warnings as follows: 

prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and will always have its default value `0'
prog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Geek.name' is never assigned to, and will always have its default value `null'

Parameterized Constructor

A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.

Example :  

// C# Program to illustrate calling of
// parameterized constructor.
using System;
namespace ParameterizedConstructorExample {
 
class Geek {
 
    // data members of the class.
    String name;
    int id;
 
    // parameterized constructor would
    // initialized data members with
    // the values of passed arguments
    // while object of that class created.
    Geek(String name, int id)
    {
        this.name = name;
        this.id = id;
    }
 
    // Main Method
    public static void Main()
    {
 
        // This will invoke parameterized
        // constructor.
        Geek geek1 = new Geek("GFG", 1);
        Console.WriteLine("GeekName = " + geek1.name +
                         " and GeekId = " + geek1.id);
    }
}
}

Output : 

GeekName = GFG and GeekId = 1 

Copy Constructor

This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance. 

Example : 


Private Constructor

If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class. 

Points To Remember :  

  • It is the implementation of a singleton class pattern.
  • use private constructor when we have only static members.
  • Using private constructor, prevents the creation of the instances of that class.

Example : 

Static Constructor

Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once. 

Points To Remember :  

  • It can’t be called directly.
  • When it is executing then the user has no control.
  • It does not take access modifiers or any parameters.
  • It is called automatically to initialize the class before the first instance created.

Example :


https://www.google.com/amp/s/www.geeksforgeeks.org/c-sharp-constructors/amp/


Difference b/w Abstraction and Encapsulation


AbstractionEncapsulation
Abstraction solves the problem in the design level.Encapsulation solves the problem in the implementation level.
Abstraction is used for hiding the unwanted data and giving only relevant data.Encapsulation is hiding the code and data into a single unit to protect the data from outer world.
Abstraction is set focus on the object instead of how it does it.Encapsulation means hiding the internal details or mechanics of how an object does something.
Abstraction is outer layout in terms of design.
For Example: - Outer Look of a iPhone, like it has a display screen.
Encapsulation is inner layout in terms of implementation.
For Example: - Inner Implementation detail of a iPhone, how Display Screen are connect with each other using circuits




Difference between Abstract Class and Interface

Abstract ClassInterface
It contains both declaration and definition part.It contains only a declaration part.
Multiple inheritance is not achieved by abstract class.Multiple inheritance is achieved by interface.
It contain constructor.It does not contain constructor.
It can contain static members.It does not contain static members.
It can contain different types of access modifiers like public, private, protected etc.It only contains public access modifier because everything in the interface is public.
The performance of an abstract class is fast.The performance of interface is slow because it requires time to search actual method in the corresponding class.
It is used to implement the core identity of class.It is used to implement peripheral abilities of class.
A class can only use one abstract class.A class can use multiple interface.
If many implementations are of the same kind and use common behavior, then it is superior to use abstract class.If many implementations only share methods, then it is superior to use Interface.
Abstract class can contain methods, fields, constants, etc.Interface can only contains methods, properties, indexers, events.
The keyword “:” can be used for implementing the Abstract class.The keyword “:” and “,” can be used for implementing the Interface.
It can be fully, partially or not implemented.It should be fully implemented.
To declare abstract class , we use abstract keyword.To declare interface, we use interface keyword.

Example of Abstract class:-

public abstract class Fruits{
public abstract void Mango();

}

Example of Interface:-

public interface Readable{
void read();
}


Difference between Class and Structure:

ClassStructure
Classes are of reference types.Structs are of value types.
All the reference types are allocated on heap memory.All the value types are allocated on stack memory.
Allocation of large reference type is cheaper than allocation of large value type.Allocation and de-allocation is cheaper in value type as compare to reference type.
Class has limitless features.Struct has limited features.
Class is generally used in large programs.Struct are used in small programs.
Classes can contain constructor or destructor.Structure does not contain parameter less constructor or destructor, but can contain Parameterized constructor or static constructor.
Classes used new keyword for creating instances.Struct can create an instance, with or without new keyword.
A Class can inherit from another class.A Struct is not allowed to inherit from another struct or class.
The data member of a class can be protected.The data member of struct can’t be protected.
Function member of the class can be virtual or abstract.Function member of the struct cannot be virtual or abstract.
Two variable of class can contain the reference of the same object and any operation on one variable can affect another variable.Each variable in struct contains its own copy of data(except in ref and out parameter variable) and any operation on one variable can not effect another variable.

// C# program to illustrate the

// concept of class

using System;


// Class Declaration

public class Author {


// Data members of class

public string name;

public string language;

public int article_no;

public int improv_no;


// Method of class

public void Details(string name, string language,

int article_no, int improv_no)

{

this.name = name;

this.language = language;

this.article_no = article_no;

this.improv_no = improv_no;


Console.WriteLine("The name of the author is : " + name

+ "\nThe name of language is : " + language

+ "\nTotal number of article published "

+ article_no + "\nTotal number of Improvements:"

+" done by author is : " + improv_no);

}


// Main Method

public static void Main(String[] args)

{


// Creating object

Author obj = new Author();


// Calling method of class

// using class object

obj.Details("Ankita", "C#", 80, 50);

}

}



Output:
The name of the author is :  Ankita
The name of language is : C#
Total number of article published  80
Total number of Improvements: done by author is : 50

// C# program to illustrate the
// concept of structure
using System;

// Defining structure
public struct Car
{

	// Declaring different data types
	public string Brand;
	public string Model;
	public string Color;
}

class GFG {

	// Main Method
	static void Main(string[] args)
	{

		// Declare c1 of type Car
		// no need to create an
		// instance using 'new' keyword
		Car c1;

		// c1's data
		c1.Brand = "Bugatti";
		c1.Model = "Bugatti Veyron EB 16.4";
		c1.Color = "Gray";

		// Displaying the values
		Console.WriteLine("Name of brand: " + c1.Brand
						+ "\nModel name: " + c1.Model
						+ "\nColor of car: " + c1.Color);
	}
}


Output:
Name of brand: Bugatti
Model name: Bugatti Veyron EB 16.4
Color of car: Gray


C# - Delegates

Delegate in C#:

  • Definition: A delegate is a type that represents references to methods with a specific signature and return type. Delegates are used to pass methods as arguments to other methods, and they allow methods to be called indirectly. They are similar to function pointers in C++, but safer and more flexible.

Simple Example of a Delegate:

csharp
using System; class Program { // Define a delegate that takes two integers and returns an integer public delegate int MathOperation(int a, int b); static void Main() { // Instantiate the delegate, assigning it the Add method MathOperation operation = Add; // Call the delegate, which invokes the Add method int result = operation(5, 3); Console.WriteLine("Result of Add: " + result); // Reassign delegate to the Subtract method operation = Subtract; // Call the delegate, which invokes the Subtract method result = operation(5, 3); Console.WriteLine("Result of Subtract: " + result); } // Method that matches the delegate signature (takes two ints, returns an int) static int Add(int x, int y) { return x + y; } // Another method that matches the delegate signature static int Subtract(int x, int y) { return x - y; } }

Output:

sql
Result of Add: 8 Result of Subtract: 2

There are three steps involved while working with delegates:

  1. Declare a delegate
  2. Set a target method
  3. Invoke a delegate

How it works:

  1. Delegate Definition: The MathOperation delegate is defined with a signature that accepts two integers and returns an integer.
  2. Delegate Instantiation: The operation delegate is instantiated and assigned the Add method.
  3. Delegate Invocation: Calling operation(5, 3) invokes the Add method indirectly.
  4. Delegate Reassignment: The delegate is reassigned to the Subtract method, allowing the same delegate to be used for a different operation.

This demonstrates how delegates can store references to methods and invoke them dynamically.


Difference between out and ref keyword in C#

out keyword

out keyword is used to pass arguments to method as a reference type and is primary used when a method has to return multiple values. 

ref keyword is also used to pass arguments to method as reference type and is used when existing variable is to be modified in a method. Following is the valid usage of ref and out keywords in C#.

IIn C#, ref and out are keywords used to pass arguments by reference to a method, meaning any changes made to the parameters inside the method are reflected outside the method as well. However, they have different behaviors.

ref Keyword

  • Definition: The ref keyword is used to pass a variable by reference. The variable passed as ref must be initialized before being passed to the method.
  • Example:
csharp
using System; class Program { static void Main() { int number = 10; // Must be initialized before passing Console.WriteLine("Before method call: " + number); ModifyNumber(ref number); Console.WriteLine("After method call: " + number); } static void ModifyNumber(ref int num) { num += 20; // Modifies the original value } }

Output:

sql
Before method call: 10 After method call: 30

out Keyword

  • Definition: The out keyword is used to pass a variable by reference, but unlike ref, the variable doesn't need to be initialized before passing. However, it must be assigned a value inside the method before the method returns.
  • Example:
csharp
using System; class Program { static void Main() { int result; // Not initialized Calculate(out result); Console.WriteLine("Result after method call: " + result); } static void Calculate(out int res) { res = 50; // Must assign a value inside the method } }

Output:

sql
Result after method call: 50

Key Differences:

  • Initialization: Variables passed with ref must be initialized before calling the method, while out does not require initialization before the method call.
  • Assignment: Methods using out are required to assign a value to the variable inside the method, whereas ref does not require it since the variable already has a value.


C# collection types are designed to store, manage and manipulate similar data more efficiently. Data manipulation includes adding, removing, finding, and inserting data in the collection. Collection types implement the following common functionality: 

  • Adding and inserting items to a collection
  • Removing items from a collection
  • Finding, sorting, searching items
  • Replacing items
  • Copy and clone collections and items
  • Capacity and Count properties to find the capacity of the collection and number of items in the collection

.NET supports two types of collections, generic collections and non-generic collections. Prior to .NET 2.0, it was just collections and when generics were added to .NET, generics collections were added as well.

Generic collections with work generic data type. Learn more about generics here: Generics in C#

The following table lists and matches these classes.

Non-generic                          Generic

ArrayList     ------------->          List

HashTable  ------------->          Dictionary

SortedList   ------------->          SortedList  

Stack           ------------->          Stack

Queue         ------------->          Queue

1. Non-Generic

In non-generic collections, each element can represent a value of a different type. The collection size is not fixed. Items from the collection can be added or removed at runtime. 

C# ArrayList

ArrayList class is a collection that can be used for any types or objects. 

  1. Arraylist is a class that is similar to an array, but it can be used to store values of various types.
  2. An Arraylist doesn't have a specific size.
  3. Any number of elements can be stored.
using System.Collections;

protected void Button1_Click(object sender, EventArgs e)
{
     ArrayList al = new ArrayList();
     string str = "kiran teja jallepalli";
     int x = 7;
     DateTime d = DateTime.Parse("8-oct-1985");
     al.Add(str);
     al.Add(x);
     al.Add(d);

     foreach (object o in al)
     {
        Response.Write(o);
        Response.Write("<br>");
     }
}
C#

Output

kiran teja jallepalli
7
10/8/1985 12:00:00 AM

Foreach Loop

It executes for each and every item that exists in the arraylist object. Every time the loop rotates it reads one item from the arraylist and assignes it to the variable.

Note: Arraylist allocates memory for 4 items, whenever an object is created. When a fifth item is added, memory for another 4 items are added. it reduces the memory allocated for the object.

Capacity: is a property that returns the number of items for for which memory is allocated.

Here is a detailed tutorial: AarrayList in C#

C# HashTable

HashTable is similar to arraylist but represents the items as a combination of a key and value.

using System.Collections;

protected void Button2_Click(object sender, EventArgs e)
{
    Hashtable ht = new Hashtable();
    ht.Add("ora", "oracle");
    ht.Add("vb", "vb.net");
    ht.Add("cs", "cs.net");
    ht.Add("asp", "asp.net");

    foreach (DictionaryEntry d in ht)
    {
       Response.Write (d.Key + " " + d.Value);
       Response.Write("<br>");
    }
}
C#

Output

vb  vb.net
asp asp.net
cs  cs.net
ora oracle 

DictonaryEntry: is a class whose object represents the data in a combination of key & value pairs.

Learn more here: HashTable in C# 

C# SortedList

  1. Is a class that has the combination of arraylist and hashtable.
  2. Represents the data as a key and value pair.
  3. Arranges all the items in sorted order. 
using System.Collections;

protected void Button3_Click(object sender, EventArgs e)
{
     SortedList sl = new SortedList();
     sl.Add("ora", "oracle");
     sl.Add("vb", "vb.net");
     sl.Add("cs", "cs.net");
     sl.Add("asp", "asp.net");

Learn more here: SortedList in C#. 

C# Stack

protected void Button4_Click(object sender, EventArgs e)
{
    Stack stk = new Stack();
    stk.Push("cs.net");
    stk.Push("vb.net");
    stk.Push("asp.net");
    stk.Push("sqlserver");

    foreach (object o in stk)
    {
       Response.Write(o + "<br>");
    }
}
C#

Output

sqlserver
asp.net
vb.net
cs.net

Here is a detailed tutorial in Stack in C#. 

C# Queue

using System.Collections;

protected void Button5_Click(object sender, EventArgs e)
{
    Queue q = new Queue();
    q.Enqueue("cs.net");
    q.Enqueue("vb.net");
    q.Enqueue("asp.net");
    q.Enqueue("sqlserver");

    foreach (object o in q)
    {
       Response.Write(o + "<br>");
    }
}
C#

Output

cs.net
vb.net
asp.net
sqlserver

Here is a detailed tutorial: Queue in C# 

2. Generic Collections

Generic Collections work on the specific type that is specified in the program whereas non-generic collections work on the object type. 

  1. Specific type
  2. Array Size is not fixed
  3. Elements can be added / removed at runtime.

C# List

using System.Collections.Generic;

protected void Button1_Click(object sender, EventArgs e)
{
    List<int> lst = new List<int>();
    lst.Add(100);
    lst.Add(200);
    lst.Add(300);
    lst.Add(400);
    foreach (int i in lst)
    {
        Response.Write(i+"<br>");
    }
}
C#

C# Dictonary

using System.Collections.Generic;

protected void Button1_Click(object sender, EventArgs e)
{
    Dictionary<int, string> dct = new Dictionary<int, string>();
    dct.Add(1, "cs.net");
    dct.Add(2, "vb.net");
    dct.Add(3, "vb.net");
    dct.Add(4, "vb.net");
    foreach (KeyValuePair<int, string> kvp in dct)
    {
        Response.Write(kvp.Key + " " + kvp.Value);
        Response.Write("<br>");
    }
}
C#

C# SortedList

using System.Collections.Generic;

protected void Button3_Click(object sender, EventArgs e)
{
    SortedList<string, string> sl = new SortedList<string, string>();
    sl.Add("ora", "oracle");
    sl.Add("vb", "vb.net");
    sl.Add("cs", "cs.net");
    sl.Add("asp", "asp.net");

ASP.NET MVC- Filters

In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides filters for this purpose.

ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes. Filters can be applied to an action method or controller in a declarative or programmatic way. Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface.

MVC provides different types of filters. The following table list filter types, built-in filters, and interface that must be implemented to create custom filters.

Filter TypeDescriptionBuilt-in FilterInterface
Authorization filtersPerforms authentication and authorizes before executing an action method.[Authorize], [RequireHttps]IAuthorizationFilter
Action filtersPerforms some operation before and after an action method executes.

 

IActionFilter
Result filtersPerforms some operation before or after the execution of the view.[OutputCache]IResultFilter
Exception filtersPerforms some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline.


 Differencce between DLL and Exe

dll is a file extension. It stands for Dynamic Link Library
EXE (Executable)'

An exe is a programDLL is a library
IEnumerable and IQueryable and what the differences are between them.

IEnumerable and IQueryable are used for data manipulation in LINQ from the database and collections.

For getting the data from the database, I have created a table named "Employee" that has some data and looks like:

Then creating the Data Context class (.dbml class) in your project that converts the database table named "Employee" as a class.

Now I will tell you the functionality and some basic differences between IEnumerable and IQueryable using the object of the Data Context class..

IEnumerable Code

SQL statement after execution of above query

After the execution of line number 18, the SQL statement will look like the following until the end:

IQueryable Code

SQL statement after execution of the preceding query

After the execution of line number 22, the SQL statement will look like:

But after the execution of line number 23, SQL statement will add the Top for the filtering.

In both syntaxes I am accessing the data from the Employee table and then taking only 3 rows from that data. 

Differences

IEnumerable

  1. IEnumerable exists in the System.Collections namespace.


     
  2. IEnumerable is suitable for querying data from in-memory collections like List, Array and so on.
     
  3. While querying data from the database, IEnumerable executes "select query" on the server-side, loads data in-memory on the client-side and then filters the data.


     
  4. IEnumerable is beneficial for LINQ to Object and LINQ to XML queries.

IQueryable

  1. IQueryable exists in the System.Linq Namespace.


     
  2. IQueryable is suitable for querying data from out-memory (like remote database, service) collections.
     
  3. While querying data from a database, IQueryable executes a "select query" on server-side with all filters. 
  4. IQueryable is beneficial for LINQ to SQL queries.



ASP.NET MVC - Action Filters


Action filter executes before and after an action method executes. Action filter attributes can be applied to an individual action method or to a controller. When an action filter is applied to a controller, it will be applied to all the controller's action methods.

[OutputCache(Duration=100)]
public ActionResult Index()
{
    return View();
}

Create a Custom Action Filter


a custom action filter in two ways, first, by implementing the IActionFilter interface and the FilterAttribute class. Second, by deriving the ActionFilterAttribute abstract class.

The IActionFilter interface include following methods to implement:

  • void OnActionExecuted(ActionExecutedContext filterContext)
  • void OnActionExecuting(ActionExecutingContext filterContext)

The ActionFilterAttribute abstract class includes the following methods to override:

  • void OnActionExecuted(ActionExecutedContext filterContext)
  • void OnActionExecuting(ActionExecutingContext filterContext)
  • void OnResultExecuted(ResultExecutedContext filterContext)
  • void OnResultExecuting(ResultExecutingContext filterContext)
public class LogAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        Log("OnActionExecuted", filterContext.RouteData); 
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Log("OnActionExecuting", filterContext.RouteData);      
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        Log("OnResultExecuted", filterContext.RouteData);      
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        Log("OnResultExecuting ", filterContext.RouteData);      
    }

    private void Log(string methodName, RouteData routeData)
    {
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0}- controller:{1} action:{2}", methodName, 
                                                                    controllerName, 
                                                                    actionName);
        Debug.WriteLine(message);
    }
}



[Log]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View();
    }
}

The above example will show the following output when browing to http://localhost/home request.

Output:
OnActionExecuting- controller:Home action:Index
OnActionExecuted- controller:Home action:Index
OnResultExecuting - controller:Home action:Index
OnResultExecuted- controller:Home action:Index



ASP.NET Core – ConfigureServices vs Configure



ConfigureServices

Even though we will almost always use this method, it is an optional method.

If ConfigureServices exists on Startup class, it will be called by the Web host. Of course, for this to happen Web host has to instantiate Startup first. Therefore, Startup constructor will execute before ConfigureServices. We will usually have our configuration and logging setup inside of the constructor.

You will notice that by default ConfigureServices has one parameter, of type IServiceCollection. IServiceCollection is a container. Adding services to this container will make them available for dependency injection.  That means we can inject those services anywhere in our application.

Let’s see an example:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IEmailSender, EmailSender>();
}

Now we can use IEmailSender anywhere we want. For example:

public HomeController(IEmailSender emailSender)
{ 
}

Now we can access an instance of IEmailSender in our controller.  And later on, we can replace the concrete implementation of this interface inside of our ConfigureServices method with something else.

We can also add an instance of the class to DI directly.

public void ConfigureServices(IServiceCollection services)
{
   var helper = new Helper();
   services.AddSingleton(helper);
}

And now we would do the following to use the Helper instance in the controller:

public HomeController(Helper helper)
{
}

Even for MVC framework itself, you will need to add it inside of ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{  
    services.AddMvc();
}

Configure

Inside of Configure method we set up middleware that handles every HTTP request that comes to our application:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseBrowserLink();

    app.UseMvc();
}

We should keep our Configure method clean and in the case of having large chunks of code that are processing request we should move those to our middleware.

Ordering matters in Configure method, so first piece of code inside of the method will process the request first. It can either make a response or pass the request to the next piece of middleware.

 

Summary

  • ConfigureServices is used to add services to our application
  • We can use services via integrated DI once we add them inside of ConfigureServices
  • Services added to DI can be utilised within our application
  • Configure method is used to set up middleware
  • We manage HTTP request pipeline inside of Configure method
  • Inside of Configure method, we write code that will process every request and eventually make a response
  • Difference Between First() And FirstOrDefault()

The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data.
 
First() will throw an exception if there is no result data, as you can see below.
 
Difference between First() and FirstOrDefault()
 FirstOrDefault() returns the default value (null) if there is no result data and you can see the result in the following screen.
 
Difference between First() and FirstOrDefault()

output. Action Results return the result to view the page for the given request.
 
result 
 

Action Result

 
Action Result is a result of action methods or return types of action methods. Action result is an abstract class. It is a base class for all type of action results. 
 
Types 
Figure 2: Types of Action Result
 
The diagram shown below describes about abstract class of Action Result. There are two methods in Action Result. One is ActionResult() and another one is ExecuteResult().
 
class 
 

Types of Action Results

 
There are different Types of action results in ASP.NET MVC. Each result has a different type of result format to view page. 
  • View Result
  • Partial View Result
  • Redirect Result
  • Redirect To Action Result
  • Redirect To Route Result
  • Json Result
  • File Result
  • Content Result

View Result

 
View result is a basic view result. It returns basic results to view page. View result can return data to view page through which class is defined in the model. View page is a simple HTML page. Here view page has “.cshtm” extension. 
  1. public ViewResult About()  
  2.        {  
  3.             ViewBag.Message = "Your application description page.";  
  4.             return View();  
  5.   
  6.        }  
View Result is a class and is derived from “ViewResultBase” class. “ViewResultBase” is derived from Action Result. View Result base class is an Action Result. Action Result is a base class of different action result.
 
result 
result 
 
View Result class is inherited from Action Result class by View Result Base class. The diagram shown above describes inheritance of Action Results.
 

Partial View Result 

 
Partial View Result is returning the result to Partial view page. Partial view is one of the views that we can call inside Normal view page.
  1. public PartialViewResult Index()  
  2. {  
  3. return PartialView("_PartialView");  
  4. }  
partial 
 
We should create a Partial view inside shared folder, otherwise we cannot access the Partial view. The diagram is shown above the Partial view page and Layout page because layout page is a Partial view. Partial View Result class is also derived from Action Result.
 
 
 
We should create a Partial view inside shared folder, otherwise we cannot access the Partial view. The diagram is shown above the Partial view page and Layout page because layout page is a Partial view. Partial View Result class is also derived from Action Result.
 

Redirect Result

 
Redirect result is returning the result to specific URL. It is rendered to the page by URL. If it gives wrong URL, it will show 404 page errors.
  1. public RedirectResult Index()  
  2. {  
  3. return Redirect("Home/Contact");  
  4. }  

Redirect to Action Result

 
Redirect to Action result is returning the result to a specified controller and action method. Controller name is optional in Redirect to Action method. If not mentioned, Controller name redirects to a mentioned action method in current Controller. Suppose action name is not available but mentioned in the current controller, then it will show 404 page error.
  1. public ActionResult Index()  
  2. {  
  3. return RedirectToAction("Login""Account");  
  4. }  

Json Result

 
Json result is a significant Action Result in MVC. It will return simple text file format and key value pairs. If we call action method, using Ajax, it should return Json result.
  1. public ActionResult Index()  
  2. {  
  3. var persons = new List<Person1>  
  4.        {  
  5.         new Person1{Id=1, FirstName="Harry", LastName="Potter"},  
  6.               new Person1{Id=2, FirstName="James", LastName="Raj"}  
  7.        };  
  8.        return Json(persons, JsonRequestBehavior.AllowGet);  
  9.   }  
Output
 
Output 
 
While returning more data in Json format, there is a need to mention maximum length. Assign maximum length of data Using “MaxJsonLength” property.
  1. public ActionResult Index()  
  2. {  
  3. var persons = new List<Person1>  
  4.        {  
  5.         new Person1{Id=1, FirstName="Harry", LastName="Potter"},  
  6.               new Person1{Id=2, FirstName="James", LastName="Raj"}  
  7.               
  8. };  
  9.   
  10.        var jsonResult = Json(persons, JsonRequestBehavior.AllowGet);  
  11.        jsonResult.MaxJsonLength = int.MaxValue;  
  12.        return jsonResult;  
  13. }  

File Result

 
File Result returns different file format view page when we implement file download concept in MVC using file result. Simple examples for file result are shown below:
  1. public ActionResult Index()  
  2. {  
  3. return File("Web.Config""text");  
  4. }  
Output
 
Output 
 

Content Result

 
Content result returns different content's format to view. MVC returns different format using content return like HTML format, Java Script format and any other format.
 
Example
  1. public ActionResult Contact()  
  2. {  
  3. ViewBag.Message = "Your contact page.";  
  4.   
  5.        return View();  
  6. }  
Output
 
Output 
  1. public ActionResult Index()  
  2. {  
  3. return Content("<script>alert('Welcome To All');</script>");  
  4. }  
Output
 
Output 


What do you mean by Microservice?

Microservices, also known as Microservices Architecture, is basically an SDLC approach in which large applications are built as a collection of small functional modules. It is one of the most widely adopted architectural concepts within software development. In addition to helping in easy maintenance, this architecture also makes development faster. Additionally, microservices are also a big asset for the latest methods of software development such as DevOps and Agile. Furthermore, it helps deliver large, complex applications promptly, frequently, and reliably. Applications are modeled as collections of services, which are: 

  • Maintainable and testable
  • Loosely coupled
  • Independently deployable
  • Designed or organized around business capabilities
  • Managed by a small team


Microservices Interview Questions for Freshers

1. Write main features of Microservices.

Some of the main features of Microservices include:

  • Decoupling: Within a system, services are largely decoupled. The application as a whole can therefore be easily constructed, altered, and scalable
  • Componentization: Microservices are viewed as independent components that can easily be exchanged or upgraded
  • Business Capabilities: Microservices are relatively simple and only focus on one service
  • Team autonomy: Each developer works independently of each other, allowing for a faster project timeline
  • Continuous Delivery: Enables frequent software releases through systematic automation of software development, testing, and approval
  • Responsibility: Microservices are not focused on applications as projects. Rather, they see applications as products they are responsible for
  • Decentralized Governance: Choosing the right tool according to the job is the goal. Developers can choose the best tools to solve their problems
  • Agility: Microservices facilitate agile development. It is possible to create new features quickly and discard them again at any time.

2. Write main components of Microservices.

Some of the main components of microservices include: 

  • Containers, Clustering, and Orchestration 
  • IaC [Infrastructure as Code Conception] 
  • Cloud Infrastructure 
  • API Gateway 
  • Enterprise Service Bus 
  • Service Delivery 

3. What are the benefits and drawbacks of Microservices?

Benefits: 

  • Self-contained, and independent deployment module. 
  • Independently managed services.   
  • In order to improve performance, the demand service can be deployed on multiple servers.   
  • It is easier to test and has fewer dependencies.  
  • A greater degree of scalability and agility.   
  • Simplicity in debugging & maintenance.  
  • Better communication between developers and business users.   
  • Development teams of a smaller size.

Drawbacks: 

  • Due to the complexity of the architecture, testing and monitoring are more difficult.  
  • Lacks the proper corporate culture for it to work.   
  • Pre-planning is essential.  
  • Complex development.  
  • Requires a cultural shift.  
  • Expensive compared to monoliths.   
  • Security implications. 
  • Maintaining the network is more difficult.  
You can download a PDF version of Microservices Interview Questions.

4. Name three common tools mostly used for microservices.

Three common tools used for microservices include: 

  • Wiremock 
  • Docker 
  • Hystrix 

5. Explain the working of Microservice Architecture.

Microservice architectures consist of the following components: 

  • Clients: Different users send requests from various devices. 
  • Identity Provider: Validate a user's or client's identity and issue security tokens. 
  • API Gateway: Handles the requests from clients. 
  • Static Content: Contains all of the system's content. 
  • Management: Services are balanced on nodes and failures are identified. 
  • Service Discovery: A guide to discovering the routes of communication between microservices. 
  • Content Delivery Network: Includes distributed network of proxy servers and their data centers. 
  • Remote Service: Provides remote access to data or information that resides on networked computers and devices. 

6. Write difference between Monolithic, SOA and Microservices Architecture.

  • Monolithic Architecture: It is "like a big container" where all the software components of an application are bundled together tightly.  It is usually built as one large system and is one code-base. 
  • SOA (Service-Oriented Architecture): It is a group of services interacting or communicating with each other. Depending on the nature of the communication, it can be simple data exchange or it could involve several services coordinating some activity.   
  • Microservice Architecture: It involves structuring an application in the form of a cluster of small, autonomous services modeled around a business domain. The functional modules can be deployed independently, are scalable, are aimed at achieving specific business goals, and communicate with each other over standard protocols. 

7. Explain spring cloud and spring boot.

Spring Cloud: In Microservices, the Spring cloud is a system that integrates with external systems. This is a short-lived framework designed to build applications quickly. It contributes significantly to microservice architecture due to its association with finite amounts of data processing. Some of the features of spring cloud are shown below:

Spring Boot: Spring Boot is an open-sourced, Java-based framework that provides its developers with a platform on which they can create stand-alone, production-grade Spring applications. In addition to reducing development time and increasing productivity, it is easily understood.  








What is LINQ?

Language-Integrated Query (LINQ) is a powerful set of technologies based on the integration of query capabilities directly into the C# language. LINQ Queries are the first-class language construct in C# .NET, just like classes, methods, events. The LINQ provides a consistent query experience to query objects (LINQ to Objects), relational databases (LINQ to SQL), and XML (LINQ to XML).

// Data source
string[] names = {"Bill", "Steve", "James", "Mohan" };

// LINQ Query 
var myLinqQuery = from name in names
                where name.Contains('a')
                select name;
    
// Query execution
foreach(var name in myLinqQuery)
    Console.Write(name + " ");

Basic Differences between Stored Procedure and Function in SQL Server

  1. The function must return a value but in Stored Procedure it is optional. Even a procedure can return zero or n values.

  2. Functions can have only input parameters for it whereas Procedures can have input or output parameters.

  3. Functions can be called from Procedure whereas Procedures cannot be called from a Function.

Advance Differences between Stored Procedure and Function in SQL Server

  1. The procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.

  2. Procedures cannot be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.

  3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.

  4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.

  5. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.

  6. An exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.

  7. We can use Transactions in Procedure whereas we can't use Transactions in Function.


Given two tables created and populated as follows:

CREATE TABLE dbo.envelope(id int, user_id int);
CREATE TABLE dbo.docs(idnum int, pageseq int, doctext varchar(100));

INSERT INTO dbo.envelope VALUES
  (1,1),
  (2,2),
  (3,3);

INSERT INTO dbo.docs(idnum,pageseq) VALUES
  (1,5),
  (2,6),
  (null,0);

What will the result be from the following query:

UPDATE docs SET doctext=pageseq FROM docs INNER JOIN envelope ON envelope.id=docs.idnum
WHERE EXISTS (
  SELECT 1 FROM dbo.docs
  WHERE id=envelope.id
);

Explain your answer.

The result of the query will be as follows:

idnum  pageseq  doctext
1      5        5
2      6        6
NULL   0        NULL

The EXISTS clause in the above query is a red herring. It will always be true since ID is not a member of dbo.docs. As such, it will refer to the envelope table comparing itself to itself!

The idnum value of NULL will not be set since the join of NULL will not return a result when attempting a match with any value of envelope.


Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).

If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query:

Select * From Emp, Dept

Explain your answer.

The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever the ‘where’ clause is omitted.



Given two tables created as follows

create table test_a(id numeric);

create table test_b(id numeric);

insert into test_a(id) values
  (10),
  (20),
  (30),
  (40),
  (50);

insert into test_b(id) values
  (10),
  (30),
  (50);

Write a query to fetch values in table test_a that are and not in test_b without using the NOT keyword.

Note, Oracle does not support the above INSERT syntax, so you would need this instead:

insert into test_a(id) values (10);
insert into test_a(id) values (20);
insert into test_a(id) values (30);
insert into test_a(id) values (40);
insert into test_a(id) values (50);
insert into test_b(id) values (10);
insert into test_b(id) values (30);
insert into test_b(id) values (50);

In SQL Server, PostgreSQL, and SQLite, this can be done using the except keyword as follows:

select * from test_a
except
select * from test_b;

In Oracle, the minus keyword is used instead. Note that if there are multiple columns, say ID and Name, the column should be explicitly stated in Oracle queries: Select ID from test_a minus select ID from test_b

MySQL does not support the except function. However, there is a standard SQL solution that works in all of the above engines, including MySQL:

select a.id
from test_a a
left join test_b b on a.id = b.id
where b.id is null;







Write a SQL query to find the 10th highest employee salary from an Employee table. Explain your answer.

(Note: You may assume that there are at least 10 records in the Employee table.)

This can be done as follows:

SELECT TOP (1) Salary FROM
(
    SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
) AS Emp ORDER BY Salary

This works as follows:

First, the SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC query will select the top 10 salaried employees in the table. However, those salaries will be listed in descending order. That was necessary for the first query to work, but now picking the top 1 from that list will give you the highest salary not the the 10th highest salary.

Therefore, the second query reorders the 10 records in ascending order (which the default sort order) and then selects the top record (which will now be the lowest of those 10 salaries).

Not all databases support the TOP keyword. For example, MySQL and PostreSQL use the LIMIT keyword, as follows:

SELECT Salary FROM
(
    SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 10
) AS Emp ORDER BY Salary LIMIT 1;

Or even more concisely, in MySQL this can be:

SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 9,1;

And in PostgreSQL this can be:

SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET


https://www.webtrainingroom.com/interview/asp-net-core-interview-questions-answers https://thinketl.com/sql-scenario-based-interview-questions/ https://mindmajix.com/sql-server-interview-questions-for-2-5-years#difference-between-coalesce-and-isnull https://www.interviewbit.com/mvc-interview-questions/amp/ https://www.interviewbit.com/entity-framework-interview-questions/



27 tricky C# interview questions and answers

Use the following questions to ensure your candidate has the necessary C# skills and expertise to succeed at your organization. We’ve included sample answers for each question so you can listen for ideal answers.

1. What is the difference between IEnumerable and IQueryable interfaces in C#? When would you use each one?

IEnumerable is used for querying in-memory collections, while IQueryable is used for querying external data sources, like databases. IQueryable allows you to write and execute more complex queries on the server.

2. What are the differences between async/await and Task.Run in C# when dealing with asynchronous code?

Async/await is used to create asynchronous methods that can be awaited without blocking the main thread. Task.Run is used to execute a delegate or lambda expression on a ThreadPool thread asynchronously. It can be helpful to offload CPU-bound work from the main thread.

3Explain the various methods of sharing data between tasks in C#.

Data can be shared between tasks using thread-safe data structures like 

ConcurrentDictionary and ConcurrentQueue or synchronization constructs like lockMonitor, and Semaphore.

4How do you implement a custom exception handling middleware in ASP.NET Core?

Here’s a summary of the process:

  1. Implement a custom middleware that handles exceptions.

  2. Use app.UseMiddleware to add the middleware to the application’s request pipeline.

  3. In the middleware, catch exceptions, log them, and return an appropriate response.

5. How do you implement a custom attribute in C#? Provide an example of how to use it to decorate a class.

Implement a custom attribute by creating a class that derives from Attribute. Add properties or fields to store data associated with the attribute. To use the attribute, apply it to classes or members using square bracket syntax. 

Here’s an example:

[AttributeUsage(AttributeTargets.Class)]

public class CustomAttribute : Attribute

{

    public string Name { get; set; }

    public CustomAttribute(string name)

    {

        Name = name;

    }

}

[Custom("ExampleClass")]

public class MyClass

{

    // Class implementation

}

6. Explain the differences between covariance and contravariance in C# for delegates and interfaces.

Covariance allows using a more derived type instead of a less derived type, while contravariance enables the opposite. In C#, covariance can be applied to interfaces using the out keyword, and contravariance can be applied using the in keyword.

7. How do you handle deadlocks in multi-threaded C# applications?

Deadlocks occur when multiple threads are blocked, waiting for each other to release resources. To handle deadlocks, follow best practices like acquiring locks in a consistent order, using timeout mechanisms, and avoiding long-running locks.

8. Explain the using directive and the using statement in C#. What are their differences?

The using directive is used to include namespaces in a file, making types in those namespaces accessible without fully qualifying their names. The using statement is used for the automatic disposal of resources that implement IDisposable.

9. Explain the differences between value types and reference types in C#.

Value types store their value directly in memory, while reference types store a reference to an object in memory. Value types are stored on the stack, and reference types are stored on the heap.

10. How do you implement a custom IComparer<T> for sorting in C#?

Create a class that implements the IComparer<T> interface, defining the Compare method for comparing two objects. Then, use an instance of this custom comparer with the Sort method of a collection to apply your customized sorting logic.

11. Explain the concept of object pooling in C# and its benefits in multi-threaded applications.

Object pooling involves reusing objects instead of creating new ones. This can improve performance and reduce garbage collection overhead, especially in multi-threaded applications, where object creation and destruction can be costly.

12. How can you improve string concatenation performance in C#?

Use StringBuilder instead of repeated string concatenation with + to improve performance, especially when concatenating or linking multiple strings together in a loop.

13. What are delegates and events in C#? Provide an example of using events in a C# application.

Delegates are function pointers that enable encapsulating a method and calling it indirectly. Events are a way to provide notifications to other parts of the application when something happens. 

Here’s an example:

public delegate void EventHandler(object sender, EventArgs e);

public class EventPublisher

{

    public event EventHandler SomethingHappened;

    public void DoSomething()

    {

        // ... do something

        OnSomethingHappened();

    }

    protected virtual void OnSomethingHappened()

    {

        SomethingHappened?.Invoke(this, EventArgs.Empty);

    }

}

14. What are the different types of garbage collection in C#? How can you configure them?

C# supports three types of garbage collection: Workstation garbage collection, Server garbage collection, and Concurrent garbage collection. You can configure garbage collection behavior using configuration settings in the app’s configuration file.

15. Explain the differences between a deep copy and a shallow copy of objects in C#. How can you perform each type of copy?

A shallow copy creates a new object but doesn’t duplicate internal references. A deep copy creates a new object and clones all internal references recursively. Shallow copying can be done using MemberwiseClone, while deep copying requires custom implementation.

16. What is reflection in C#? How is it useful, and what are its limitations?

Reflection allows inspecting and manipulating types, methods, properties, etc., at runtime. It’s useful for building generic frameworks and creating dynamic and extensible applications. However, it can be slower and lacks compile-time safety.

17. What is the purpose of the yield keyword in C#? Provide an example of using it with an iterator.

The yield keyword is used to create an iterator in C#. It allows you to return a sequence of values without building the entire sequence in memory before returning it. 

For example:

public IEnumerable<int> GetNumbers()

{

    for (int i = 0; i < 10; i++)

    {

        yield return i;

    }

}

18. Explain how to implement a custom serializer and deserializer for a complex object in C#.

You can implement custom serialization logic by manually converting the object’s properties to a serialized format (e.g., JSON or XML). Then, implement the deserialization logic to read the serialized data and recreate the object.

19. Explain the differences between Memory<T> and Span<T> in C#. When would you use one over the other?

Memory<T> represents a chunk of memory that can be read from and written to. Span<T> is a lightweight view of a portion of an array or memory. 

Use Memory<T> when you need a dynamically allocated memory block and Span<T> to work with a portion of an existing array or memory.

20. How can you optimize memory usage and performance when working with large data collections in C#?

You can consider using data structures that are more memory-efficient for specific scenarios, like BitArray for managing sets of bits or HashSet<T> for effective membership checks. Also, you can use streaming and lazy-loading techniques to avoid loading the entire data set into memory.

21. What are extension methods in C#? Provide an example of using an extension method with an existing class.

Extension methods are created by defining static methods within static classes. The “this” keyword is used in the method's parameter to indicate the type being extended.

For example:

public static class StringExtensions{ public static bool IsPalindrome(this string str)

    {

        // Check if the string is a palindrome

        // ...

    }

}

// Usage:

string word = "racecar";

bool isPalindrome = word.IsPalindrome(); // true

22. How do you work with parallelism and concurrency in C#? Explain the differences between Parallel.ForEach and PLINQ (Parallel LINQ).

Parallel.ForEach is used to parallelize the iteration over a collection, while PLINQ allows performing parallel queries on data using LINQ. Use Parallel.ForEach when you need to apply a function to each element of a collection in parallel. Use PLINQ when you want to perform data queries in parallel.

23. How does the volatile keyword work in C#? When and how should you use it?

The volatile keyword is used to ensure that the value of a variable is always read from and written to the main memory, not from a cache. Use it when you have a variable shared between multiple threads and want to avoid potential visibility issues or stale values.

24. Explain the differences between async void and async Task in C#. When would you use one over the other?

async void is used for event handlers and should be avoided in most other scenarios since it makes error handling more difficult. async Task is used for asynchronous methods that return a result and allow better error handling through Tasks’ Exception property.

25. What is boxing and unboxing in C#? How can you avoid performance issues related to boxing?

Boxing is the process of converting a value type to an object type, and unboxing is the reverse process. Boxing and unboxing can cause performance overhead. To avoid it, use generics (List<T>, Dictionary<TKey, TValue>, etc.) over non-generic collections (ArrayListHashtable, etc.), and use generic versions of interfaces like IEnumerable<T> instead of non-generic versions like IEnumerable.

26. What is a Singleton design pattern?

The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It typically involves a private constructor and a static method to retrieve the instance.

27. Explain the Factory Method design pattern.

The factory Method pattern defines an interface for creating objects, but allows the sub class to decide which class to instantiate. It promotes loose coupling between the client code and the objects.


Here are some of the top **C# interview questions and answers** to help you prepare effectively:


---


### 1. **What is C#?**

**Answer:**  

C# is a modern, object-oriented, and type-safe programming language developed by Microsoft. It runs on the .NET Framework or .NET Core and is used for building a wide variety of applications, including web, desktop, and mobile applications.


---


### 2. **Explain the difference between `ref` and `out` parameters.**

**Answer:**  

- `ref`: The variable must be initialized before being passed to the method. It allows both input and output.  

- `out`: The variable doesn’t need to be initialized before being passed. It is meant to be assigned within the method and is only used for output.


---


### 3. **What are value types and reference types in C#?**

**Answer:**  

- **Value Types**: Store data directly (e.g., `int`, `float`, `bool`, `struct`). Stored on the stack.  

- **Reference Types**: Store references to memory addresses (e.g., `class`, `array`, `string`). Stored on the heap.


---


### 4. **What is the difference between `abstract class` and `interface`?**

**Answer:**  

- **Abstract Class**: Can have both abstract methods (without implementation) and concrete methods (with implementation). Supports fields and access modifiers.  

- **Interface**: Can only have method signatures (in older C# versions) but no fields. All members are public by default.


---


### 5. **What is the difference between `const`, `readonly`, and `static`?**

**Answer:**  

- **const**: A compile-time constant that cannot be changed after being defined.  

- **readonly**: A runtime constant that can be initialized in the constructor but cannot be modified later.  

- **static**: Indicates a member belongs to the class rather than an instance. It can be accessed without creating an object.


---


### 6. **What is the difference between `==` and `.Equals()` in C#?**

**Answer:**  

- `==`: Compares object references for reference types and actual values for value types.  

- `.Equals()`: Checks for value equality and can be overridden for custom behavior in classes.


The == operator and the .Equals() method are both used to compare values in C#, but they differ in behavior and purpose. Here's the difference:

1. == Operator

  • Purpose: Used for value comparison or reference comparison, depending on the data type.
  • Behavior:
    • For value types (like int, float, bool, etc.), it compares the actual values.
    • For reference types (like object, string, or user-defined classes), it compares references (memory addresses) unless the == operator is overridden to compare values.
  • Example:
    csharp
    int a = 10, b = 10; Console.WriteLine(a == b); // True (value comparison) string s1 = "hello"; string s2 = "hello"; Console.WriteLine(s1 == s2); // True (value comparison due to string interning) object o1 = new object(); object o2 = new object(); Console.WriteLine(o1 == o2); // False (reference comparison)

2. .Equals() Method

  • Purpose: Determines whether two objects are equal. It is more customizable and can be overridden to define specific equality logic.
  • Behavior:
    • For value types, it behaves like == (compares actual values).
    • For reference types, it defaults to reference comparison unless overridden.
  • Example:
    csharp
    int a = 10, b = 10; Console.WriteLine(a.Equals(b)); // True (value comparison) string s1 = "hello"; string s2 = "hello"; Console.WriteLine(s1.Equals(s2)); // True (value comparison) object o1 = new object(); object o2 = new object(); Console.WriteLine(o1.Equals(o2)); // False (reference comparison) object o3 = o1; Console.WriteLine(o1.Equals(o3)); // True (same reference)

Key Differences

Aspect== Operator.Equals() Method
PurposeCompares values or referencesCompares object equality
CustomizableCan be overloaded in user-defined typesCan be overridden in the Equals method
Reference TypesDefault: compares referencesDefault: compares references unless overridden
Value TypesCompares valuesCompares values

Example with Custom Class

csharp
class Person { public string Name { get; set; } public override bool Equals(object obj) { if (obj is Person other) return this.Name == other.Name; return false; } } Person p1 = new Person { Name = "Alice" }; Person p2 = new Person { Name = "Alice" }; Console.WriteLine(p1 == p2); // False (reference comparison) Console.WriteLine(p1.Equals(p2)); // True (custom equality)

In summary:

  • Use == for simple value comparisons or if you know the operator has been overloaded appropriately.
  • Use .Equals() for more specific equality checks, especially when working with objects.


---


### 7. **What is polymorphism? How is it implemented in C#?**

**Answer:**  

Polymorphism allows methods to perform differently based on the context.  

- **Compile-time Polymorphism**: Achieved through method overloading.  

- **Runtime Polymorphism**: Achieved through method overriding with `virtual` and `override` keywords.


---


### 8. **What is the difference between `dispose` and `finalize`?**

**Answer:**  

- **Dispose()**: Explicitly releases unmanaged resources. Part of `IDisposable` interface.  

- **Finalize()**: Implicitly releases resources before garbage collection. Declared using a destructor in C# (`~ClassName()`).


---


### 9. **What are delegates in C#?**

**Answer:**  

A delegate is a type-safe pointer to a method. It allows methods to be passed as parameters and is used for callbacks, events, and LINQ.  

**Example:**  

```csharp

public delegate void PrintMessage(string message);  

PrintMessage print = Console.WriteLine;  

print("Hello, Delegates!");

```


---


### 10. **What are generics in C#?**

**Answer:**  

Generics allow you to define type-safe data structures and methods without specifying the data type in advance.  

**Example:**  

```csharp

List<int> numbers = new List<int>();

```


---


### 11. **What is LINQ?**

**Answer:**  

Language Integrated Query (LINQ) is used to query collections in a type-safe way. Examples include LINQ to Objects, LINQ to SQL, and LINQ to XML.


---


### 12. **What is the difference between `String` and `StringBuilder`?**

**Answer:**  

- **String**: Immutable, meaning a new string is created in memory for every modification.  

- **StringBuilder**: Mutable, efficient for repeated modifications.


---


### 13. **What is the difference between `IEnumerable` and `IQueryable`?**

**Answer:**  

- **IEnumerable**: Used for in-memory collection iteration. Executes queries in-memory.  

- **IQueryable**: Used for querying data from out-of-memory sources like databases. Queries are executed on the server.


---


### 14. **What are the access modifiers in C#?**

**Answer:**  

- `public`: Accessible anywhere.  

- `private`: Accessible only within the containing class.  

- `protected`: Accessible within the class and its derived classes.  

- `internal`: Accessible within the same assembly.  

- `protected internal`: Combination of `protected` and `internal`.


---


### 15. **What is the difference between `Task` and `Thread`?**

**Answer:**  

- **Task**: Higher-level abstraction for asynchronous operations, part of the TPL (Task Parallel Library).  

- **Thread**: Represents a low-level execution path managed manually.


---


### 16. **What is dependency injection in C#?**

**Answer:**  

Dependency Injection (DI) is a design pattern that provides a way to supply an object’s dependencies at runtime, promoting loose coupling. Implemented via constructor injection, property injection, or method injection.


---


### 17. **What are extension methods?**

**Answer:**  

Extension methods allow adding methods to existing types without modifying them.  

**Example:**  

```csharp

public static class StringExtensions  

{  

    public static int WordCount(this string str) => str.Split(' ').Length;  

}

```


---


Let me know if you'd like more detailed examples or additional questions!






SOLID Principles in .NET

SOLID is an acronym for five object-oriented design principles that help create maintainable, scalable, and testable code.


1. S — Single Responsibility Principle (SRP)

A class should have only one reason to change.

Each class handles one concern only.

csharp
// BAD - handles both order logic AND email sending
public class OrderService
{
    public void PlaceOrder(Order order) { /* save order */ }
    public void SendConfirmationEmail(Order order) { /* send email */ }
}

// GOOD - separated responsibilities
public class OrderService
{
    public void PlaceOrder(Order order) { /* save order */ }
}

public class EmailService
{
    public void SendConfirmationEmail(Order order) { /* send email */ }
}

2. O — Open/Closed Principle (OCP)

Classes should be open for extension, but closed for modification.

Add new behavior via inheritance/interfaces, not by changing existing code.

csharp
// BAD - adding a new discount means modifying this class
public class DiscountCalculator
{
    public decimal Calculate(string type, decimal price)
    {
        if (type == "seasonal") return price * 0.9m;
        if (type == "loyalty")  return price * 0.85m;
        return price;
    }
}

// GOOD - extend without touching existing code
public interface IDiscount
{
    decimal Apply(decimal price);
}

public class SeasonalDiscount : IDiscount
{
    public decimal Apply(decimal price) => price * 0.9m;
}

public class LoyaltyDiscount : IDiscount
{
    public decimal Apply(decimal price) => price * 0.85m;
}

public class DiscountCalculator
{
    public decimal Calculate(IDiscount discount, decimal price)
        => discount.Apply(price);
}

3. L — Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types without breaking behavior.

csharp
// BAD - Square breaks Rectangle's contract
public class Rectangle
{
    public virtual int Width  { get; set; }
    public virtual int Height { get; set; }
    public int Area() => Width * Height;
}

public class Square : Rectangle
{
    public override int Width  { set { base.Width = base.Height = value; } }
    public override int Height { set { base.Width = base.Height = value; } }
    // Substituting Square for Rectangle causes unexpected behavior
}

// GOOD - use a common abstraction instead
public interface IShape
{
    int Area();
}

public class Rectangle : IShape
{
    public int Width { get; set; }
    public int Height { get; set; }
    public int Area() => Width * Height;
}

public class Square : IShape
{
    public int Side { get; set; }
    public int Area() => Side * Side;
}

4. I — Interface Segregation Principle (ISP)

Clients should not be forced to depend on interfaces they don't use.

Split large interfaces into smaller, focused ones.

csharp
// BAD - Report printer forced to implement Export
public interface IDocument
{
    void Print();
    void Save();
    void Export();
}

// GOOD - segregated interfaces
public interface IPrintable  { void Print(); }
public interface ISaveable   { void Save();  }
public interface IExportable { void Export(); }

public class ReportDocument : IPrintable, ISaveable
{
    public void Print() { /* ... */ }
    public void Save()  { /* ... */ }
    // No need to implement Export
}

5. D — Dependency Inversion Principle (DIP)

Depend on abstractions, not on concrete implementations.

This is the foundation of Dependency Injection in ASP.NET.

csharp
// BAD - tightly coupled to a concrete class
public class OrderController
{
    private SqlOrderRepository _repo = new SqlOrderRepository();
}

// GOOD - depends on abstraction; implementation injected
public interface IOrderRepository
{
    Order GetById(int id);
    void Save(Order order);
}

public class SqlOrderRepository : IOrderRepository
{
    public Order GetById(int id) { /* ... */ return null; }
    public void Save(Order order) { /* ... */ }
}

public class OrderController : Controller
{
    private readonly IOrderRepository _repo;

    public OrderController(IOrderRepository repo)  // injected
    {
        _repo = repo;
    }
}

// In Startup.cs / Program.cs
services.AddScoped<IOrderRepository, SqlOrderRepository>();

Quick Reference

PrincipleKey QuestionSolution
SRPDoes this class do too much?Split into focused classes
OCPCan I extend without editing?Use interfaces/inheritance
LSPCan I swap subclasses safely?Honor base class contracts
ISPAre clients forced to implement unneeded members?Split large interfaces
DIPAm I newing up dependencies?Inject via interface

In your ASP.NET MVC / ERP work, DIP is the most impactful — your DAL interfaces (IPickListRepository, etc.) and controller constructor injection already follow this pattern naturally.


.NET Senior Developer

Interview Questions & Answers

Based on JD: C#, ASP.NET MVC, Web API, EF, ReactJS, SQL, Security, CI/CD

 

Section 1: C# & .NET Core

 

Q1. What are the key differences between .NET Framework and .NET Core?

.NET Framework is Windows-only, ships with the OS, and supports legacy technologies like Web Forms and WCF. .NET Core (now .NET 5+) is cross-platform (Windows/Linux/macOS), open-source, modular, and optimized for performance.

Key Differences:

• Cross-platform: .NET Core runs on Linux/macOS; .NET Framework does not.

• Performance: .NET Core has better throughput (Kestrel web server is much faster than IIS-only).

• Deployment: .NET Core supports self-contained deployments (no runtime install needed on server).

• Side-by-side: Multiple .NET Core versions can run on the same machine.

• Future: Microsoft is investing only in .NET 5+ (Core successor). .NET Framework is in maintenance mode.

💡 Tip: For new enterprise projects, always choose .NET 6/8 LTS. Migrate legacy .NET Framework apps when feasible.

 

Q2. Explain async/await in C#. What happens if you call .Result on an async method?

async/await is a syntactic sugar over the Task Parallel Library (TPL). When you await a task, the current thread is released to do other work. When the awaited task completes, execution resumes.

public async Task<string> GetDataAsync() {

var result = await httpClient.GetStringAsync(url); // thread released here

return result; // resumes here when done

}

Calling .Result (Deadlock Risk):

Calling .Result or .Wait() on an async method blocks the current thread synchronously. In ASP.NET (classic), the SynchronizationContext means the thread is waiting for itself to resume — causing a deadlock.

var data = GetDataAsync().Result; // DEADLOCK in ASP.NET classic!

In ASP.NET Core there is no SynchronizationContext, so .Result won't deadlock — but it still wastes a thread. Always use await instead.

💡 Tip: Never use .Result or .Wait() in async code. Use await all the way up the call stack (async all the way).

 

Q3. What is the difference between IEnumerable, IQueryable, and IList?

IEnumerable<T>:

• In-memory iteration only. Executes query on the client side.

• Suitable for LINQ to Objects (lists, arrays).

• CODE:IEnumerable<User> users = dbContext.Users.Where(u => u.Active);

  All users loaded into memory THEN filtered.

IQueryable<T>:

• Builds an expression tree. Executes query on the database (translated to SQL).

• CODE:IQueryable<User> users = dbContext.Users.Where(u => u.Active);

  Only matching rows fetched from DB — far more efficient.

IList<T>:

• Already materialized in memory. Supports indexing, Count, Add, Remove.

• Use when you need random access or to modify the collection.

💡 Tip: Always use IQueryable when querying databases with EF. Use IEnumerable when working with in-memory collections. Use IList when you need index access.

 

Q4. How does garbage collection work in .NET? What is Gen 0, Gen 1, Gen 2?

The .NET Garbage Collector (GC) automatically manages memory. Objects are organized into 3 generations based on their expected lifetime.

Generations:

• Gen 0: Short-lived objects (local variables, temp objects). Collected most frequently. Very fast.

• Gen 1: Objects that survived Gen 0 collection. Buffer between short and long-lived.

• Gen 2: Long-lived objects (static data, large objects, application-lifetime objects). Collected least frequently.

How it works:

1. Object allocated → starts in Gen 0.

2. If it survives a Gen 0 collection → promoted to Gen 1.

3. If it survives Gen 1 → promoted to Gen 2.

4. Large Object Heap (LOH): Objects > 85KB go directly here (always Gen 2).

Triggering GC:

• Gen 0 fills up (most common), system memory pressure, or GC.Collect() call.

💡 Tip: Avoid allocating large objects frequently. Use object pooling (ArrayPool<T>) for high-performance scenarios.

 

Q5. What are records, structs, and classes in C# — when would you use each?

Class (Reference Type):

• Stored on the heap. Passed by reference. Supports inheritance.

• Use for: complex objects, services, entities with behavior.

Struct (Value Type):

• Stored on the stack. Passed by value (copied). No inheritance.

• Use for: small, immutable data like coordinates, Color, DateTime.

struct Point { public int X; public int Y; }

Record (C# 9+):

• Reference type with value-based equality and immutability by default.

• Ideal for DTOs, API response models, data transfer.

record Person(string Name, int Age); // immutable, with-expression support

var p1 = new Person("Anil", 30);

var p2 = p1 with { Age = 31 }; // creates new record

💡 Tip: Use records for DTOs/API models, structs for small value-semantics data, classes for everything else.

 

Q6. Explain ref, out, and in keywords in C#.

ref — Pass by reference (must be initialized before passing):

void Double(ref int x) { x *= 2; }

int n = 5; Double(ref n); // n is now 10

out — Pass by reference, but doesn't need to be initialized. Must be assigned inside method:

bool TryParse(string s, out int result) { result = int.Parse(s); return true; }

if (int.TryParse("42", out int val)) { ... }

in — Pass by reference but READ-ONLY inside the method (prevents defensive copy):

void Print(in Point p) { Console.WriteLine(p.X); } // cannot modify p

💡 Tip: Use out for multiple return values (like TryParse pattern). Use in for large structs to avoid copying without allowing modification.

 

Section 2: ASP.NET MVC & Web API

 

Q7. What is the request lifecycle in ASP.NET MVC?

Full Request Pipeline:

1. HTTP Request arrives → Kestrel (or IIS) receives it.

2. Middleware Pipeline: Authentication → Authorization → Routing → Endpoint.

3. Routing: Matches URL pattern to Controller + Action.

4. Model Binding: Request data (query string, body, route) bound to action parameters.

5. Action Filters (OnActionExecuting): Runs before action.

6. Action Method executes → returns ActionResult.

7. Action Filters (OnActionExecuted): Runs after action.

8. Result Filters: Before/After result execution.

9. View Engine renders the View (for MVC) or JSON serialized (for API).

10. Response sent back to client.

💡 Tip: In your ERP MVC app, authorization filters run before your controller action — that's where plant-based authorization is best enforced.

 

Q8. What is the difference between ActionResult and IActionResult?

IActionResult (interface):

• Base interface for all action results. Allows returning different types.

public IActionResult Get() { return Ok(data); // or NotFound(), BadRequest() }

ActionResult (abstract class):

• Implements IActionResult. Base class for ViewResult, JsonResult, RedirectResult, etc.

ActionResult<T> (C# generic, .NET Core):

• Allows returning either T directly or an IActionResult, useful for Swagger/OpenAPI type inference.

public ActionResult<List<Order>> GetOrders() {

if (!found) return NotFound();

return orders; // implicit conversion to OkObjectResult

}

💡 Tip: Prefer IActionResult or ActionResult<T> in Web API controllers for flexibility and better Swagger documentation.

 

Q9. How do you implement versioning in Web API?

Install: Microsoft.AspNetCore.Mvc.Versioning

3 Strategies:

1. URL Segment: /api/v1/orders, /api/v2/orders

2. Query String: /api/orders?api-version=1.0

3. HTTP Header: api-version: 1.0

// Startup.cs

services.AddApiVersioning(opt => {

opt.DefaultApiVersion = new ApiVersion(1, 0);

opt.AssumeDefaultVersionWhenUnspecified = true;

opt.ReportApiVersions = true;

});

// Controller

[ApiVersion("1.0")]

[Route("api/v{version:apiVersion}/orders")]

public class OrdersV1Controller : ControllerBase { }

💡 Tip: Use URL segment versioning for public APIs (most visible). Use header versioning for internal/partner APIs.

 

Q10. What are Action Filters and Middleware — how are they different?

Middleware:

• Runs for ALL requests in the pipeline, regardless of routing.

• Applied globally. Handles cross-cutting concerns like logging, auth, CORS.

• Runs before MVC even knows which controller to call.

app.Use(async (context, next) => { /* runs for every request */ await next(); });

Action Filters:

• Runs only for MVC/API controller actions.

• Has access to action parameters and ActionContext.

• Can be applied globally, per-controller, or per-action.

[ServiceFilter(typeof(PlantAuthorizationFilter))] // per-action

public class PlantAuthorizationFilter : IActionFilter {

public void OnActionExecuting(ActionExecutingContext context) { /* check plant */ }

}

Decision Guide:

• Need to run before routing? → Middleware.

• Need action parameters or controller context? → Action Filter.

💡 Tip: Your plant-based authorization is a perfect use case for an Action Filter — it needs to inspect route/session data and short-circuit the action.

 

Q11. How do you handle global exception handling in Web API?

Option 1 — Exception Middleware (Recommended in .NET Core):

app.UseExceptionHandler(appError => {

appError.Run(async context => {

context.Response.StatusCode = 500;

context.Response.ContentType = "application/json";

var ex = context.Features.Get<IExceptionHandlerFeature>();

await context.Response.WriteAsync(JsonSerializer.Serialize(

new { error = ex?.Error.Message }));

});

});

Option 2 — IExceptionFilter:

public class GlobalExceptionFilter : IExceptionFilter {

public void OnException(ExceptionContext context) {

context.Result = new ObjectResult(new { error = context.Exception.Message })

{ StatusCode = 500 };

context.ExceptionHandled = true;

}

}

services.AddControllers(opt => opt.Filters.Add<GlobalExceptionFilter>());

💡 Tip: Always log the full exception (with stack trace) internally but return only a safe message to the client.

 

Q12. What is the difference between [FromBody], [FromQuery], and [FromRoute]?

These attributes control how ASP.NET Core binds request data to action parameters.

[FromRoute] — Binds from URL path segments:

// GET /api/orders/42

public IActionResult Get([FromRoute] int id) { }

[FromQuery] — Binds from query string parameters:

// GET /api/orders?status=pending&page=1

public IActionResult Get([FromQuery] string status, [FromQuery] int page) { }

[FromBody] — Binds from request body (JSON/XML). Only ONE [FromBody] per action:

// POST /api/orders with JSON body

public IActionResult Create([FromBody] OrderDto order) { }

Other useful ones:

• [FromHeader] — from HTTP headers (e.g., Authorization token).

• [FromForm] — from multipart/form-data (file uploads).

💡 Tip: In Web API, complex objects default to [FromBody]. Simple types (int, string) default to [FromRoute] or [FromQuery].

 

Section 3: Entity Framework & LINQ

 

Q13. What is the difference between Code First and Database First in EF?

Database First (what you use in your ERP with EDMX):

• You create the database schema first, then generate C# entity classes and EDMX from it.

• Good for existing databases. Database is the source of truth.

• CODE:Scaffold-DbContext "Server=..." Microsoft.EntityFrameworkCore.SqlServer

Code First:

• You write C# classes first, EF generates the database from them using migrations.

• Database is derived from code. Code is the source of truth.

public class Order { public int Id { get; set; } public string Status { get; set; } }

Add-Migration InitialCreate

Update-Database

Model First:

• Design entity model visually in EDMX designer, generate both DB and classes from it.

💡 Tip: For new projects, Code First with migrations is recommended. For your ERP legacy system, Database First/EDMX is the right approach.

 

Q14. Explain lazy loading, eager loading, and explicit loading in Entity Framework.

Lazy Loading (default in EF6, opt-in in EF Core):

• Related data is loaded automatically when you first access the navigation property.

• Can cause N+1 problem if used in a loop.

var orders = db.Orders.ToList(); // SQL 1

var items = orders[0].OrderItems.ToList(); // SQL 2 (lazy load, extra query per order!)

Eager Loading — use .Include() to load related data upfront in one query:

var orders = db.Orders.Include(o => o.OrderItems).ToList(); // Single SQL with JOIN

Explicit Loading — manually trigger load when needed:

var order = db.Orders.Find(1);

db.Entry(order).Collection(o => o.OrderItems).Load(); // load explicitly

💡 Tip: Always prefer Eager Loading (Include) in Web API and MVC. Lazy loading is convenient but unpredictable in terms of SQL queries generated.

 

Q15. What is the N+1 query problem? How do you fix it?

N+1 Problem:

You execute 1 query to get N records, then N additional queries to get related data for each.

var orders = db.Orders.ToList(); // 1 query → returns 100 orders

foreach (var o in orders) {

var customer = o.Customer.Name; // 100 individual queries! = N+1

}

Total: 101 SQL queries instead of 1!

Fix — Use .Include() (Eager Loading):

var orders = db.Orders.Include(o => o.Customer).ToList(); // 1 query with JOIN

Fix — Use Select/Projection to load only what you need:

var result = db.Orders

.Select(o => new { o.Id, CustomerName = o.Customer.Name })

.ToList(); // single optimized query

💡 Tip: Enable SQL logging during development to catch N+1 queries early: services.AddDbContext<Db>(opt => opt.LogTo(Console.WriteLine));

 

Q16. How does SaveChanges() work internally in EF?

SaveChanges() persists all pending changes tracked by the DbContext to the database in a single transaction.

Internal Steps:

1. Change Tracker scans all tracked entities for state changes (Added, Modified, Deleted, Unchanged).

2. Generates appropriate SQL: INSERT for Added, UPDATE for Modified, DELETE for Deleted.

3. Wraps all SQL in a single database transaction.

4. Executes SQL against the database.

5. If all succeed → commits transaction. Any failure → rolls back entire transaction.

6. Updates entity states back to Unchanged.

db.Orders.Add(new Order { ... }); // State: Added

existingOrder.Status = "Shipped"; // State: Modified

db.Orders.Remove(order); // State: Deleted

db.SaveChanges(); // All 3 SQL statements in one transaction

💡 Tip: Call SaveChanges() once per unit of work, not after every single change. Use SaveChangesAsync() in async code.

 

Q17. Write a LINQ query to group orders by customer and get the total amount.

Method Syntax:

var result = db.Orders

.GroupBy(o => o.CustomerId)

.Select(g => new {

CustomerId = g.Key,

TotalAmount = g.Sum(o => o.Amount),

OrderCount = g.Count()

})

.ToList();

Query Syntax:

var result = from o in db.Orders

group o by o.CustomerId into g

select new {

CustomerId = g.Key,

TotalAmount = g.Sum(x => x.Amount),

OrderCount = g.Count()

};

💡 Tip: GroupBy translates to SQL GROUP BY when used with IQueryable — very efficient. Avoid GroupBy on IEnumerable for large datasets (groups in memory).

 

Q18. What is the difference between .Select() and .SelectMany()?

.Select() — Projects each element to a new form (1-to-1 mapping):

var names = orders.Select(o => o.CustomerName); // IEnumerable<string>

var nested = orders.Select(o => o.OrderItems); // IEnumerable<IEnumerable<Item>> (nested!)

.SelectMany() — Flattens nested collections (1-to-many, flattened):

var allItems = orders.SelectMany(o => o.OrderItems); // IEnumerable<Item> (flat list)

// All order items across all orders in one flat collection

Real-world analogy:

• Select: each student → their grades list → you get a list of lists.

• SelectMany: each student → their grades → you get one flat list of all grades.

💡 Tip: Use SelectMany when you have a collection of collections and want to work with all items as a single sequence.

 

Section 4: Design Patterns & DI

 

Q19. Explain the Repository Pattern and Unit of Work — why use them together?

Repository Pattern:

• Abstracts data access logic behind an interface. Controllers/services don't talk to DB directly.

public interface IOrderRepository {

Order GetById(int id);

void Add(Order order);

IEnumerable<Order> GetByPlant(string plant);

}

Unit of Work (UoW):

• Coordinates multiple repositories sharing the same DbContext/transaction.

• Ensures all changes across repositories are committed or rolled back together.

public interface IUnitOfWork {

IOrderRepository Orders { get; }

ICustomerRepository Customers { get; }

int Complete(); // calls SaveChanges()

}

Why together?

• Repository alone: each repo has its own SaveChanges → inconsistent transactions.

• UoW: one SaveChanges() across all repos → atomic transaction.

💡 Tip: In your ERP's PickList module, UoW ensures that saving a PickList header and its detail lines happens atomically.

 

Q20. What is Dependency Injection? AddScoped vs AddSingleton vs AddTransient?

Dependency Injection (DI):

Instead of a class creating its own dependencies, they are injected from outside. This promotes loose coupling and testability.

// Without DI (tightly coupled)

public class OrderService { var repo = new SqlOrderRepo(); }

// With DI (loosely coupled)

public class OrderService { public OrderService(IOrderRepo repo) { _repo = repo; } }

Lifetimes:

• AddTransient: New instance created every time it's requested. Use for lightweight, stateless services.

services.AddTransient<IEmailService, SmtpEmailService>();

• AddScoped: One instance per HTTP request. Shared within the same request. Perfect for DbContext.

services.AddScoped<IOrderRepository, SqlOrderRepository>();

services.AddDbContext<AppDbContext>(); // Scoped by default

• AddSingleton: One instance for the entire app lifetime. Use for shared state/caches.

services.AddSingleton<ICacheService, MemoryCacheService>();

💡 Tip: Rule of thumb: Services → Scoped. Utilities → Transient. Config/Cache → Singleton. Never inject Scoped into Singleton!

 

Q21. What design pattern for multiple discount types without modifying existing code?

Answer: Open/Closed Principle + Strategy Pattern.

Strategy Pattern:

Define a family of algorithms, encapsulate each one, and make them interchangeable.

public interface IDiscountStrategy { decimal Apply(decimal price); }

public class SeasonalDiscount : IDiscountStrategy {

public decimal Apply(decimal price) => price * 0.90m; }

public class LoyaltyDiscount : IDiscountStrategy {

public decimal Apply(decimal price) => price * 0.85m; }

public class NoDiscount : IDiscountStrategy {

public decimal Apply(decimal price) => price; }

// Context class — never changes when new discounts added

public class PriceCalculator {

public decimal Calculate(IDiscountStrategy strategy, decimal price)

=> strategy.Apply(price);

}

Adding a new discount (e.g., VIPDiscount) means adding a new class — zero changes to existing code.

💡 Tip: This is exactly how you should handle multiple authorization rules (per plant, per role, per module) — strategy/policy pattern.

 

Q22. Explain the Factory and Builder patterns with a real-world example.

Factory Pattern — Creates objects without exposing creation logic:

public abstract class Notification { public abstract void Send(); }

public class EmailNotification : Notification { public override void Send() { ... } }

public class SmsNotification : Notification { public override void Send() { ... } }

public static class NotificationFactory {

public static Notification Create(string type) {

return type == "email" ? new EmailNotification() : new SmsNotification();

}

}

Builder Pattern — Constructs complex objects step by step:

var report = new ReportBuilder()

.SetTitle("Sales Report")

.SetDateRange(startDate, endDate)

.IncludeChart(true)

.SetPlant("PUNE01")

.Build();

When to use:

• Factory: when the type of object to create varies based on input.

• Builder: when object construction requires many optional parameters or steps.

 

Q23. What is the CQRS pattern? Have you used MediatR?

CQRS (Command Query Responsibility Segregation):

Separates READ operations (Queries) from WRITE operations (Commands) into different models/handlers.

• Query: Returns data, no side effects. (GetOrderById, GetPickList)

• Command: Changes state, returns success/failure. (CreateOrder, UpdatePickList)

MediatR — a .NET library implementing CQRS + Mediator pattern:

// Command

public record CreateOrderCommand(string CustomerCode, decimal Amount) : IRequest<int>;

public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, int> {

public async Task<int> Handle(CreateOrderCommand cmd, CancellationToken ct) {

// create order, return id

}

}

// In controller

var orderId = await _mediator.Send(new CreateOrderCommand(code, amount));

Benefits:

• Controllers become thin (just dispatch commands/queries).

• Handlers are independently testable.

• Read model can be optimized separately from write model.

💡 Tip: MediatR also supports pipeline behaviors — perfect for cross-cutting concerns like validation (FluentValidation), logging, and authorization.

 

Section 5: Multi-Tenancy

 

Q24. How would you design a multi-tenant web application in .NET Core?

Multi-tenancy means one application instance serves multiple tenants (clients/companies) with data isolation.

Key Components:

1. Tenant Identification: Determine which tenant is making the request.

   • Subdomain: tenant1.app.com, tenant2.app.com

   • Route: /tenant1/orders

   • Header: X-Tenant-Id: tenant1

   • JWT claim: tenantId in the token

2. Tenant Resolution Middleware:

public class TenantMiddleware {

public async Task InvokeAsync(HttpContext context) {

var host = context.Request.Host.Host; // e.g., tenant1.app.com

var tenantId = ResolveTenantFromHost(host);

context.Items["TenantId"] = tenantId;

await _next(context);

}

}

3. Data Isolation: Filter all queries by TenantId using EF Query Filters.

modelBuilder.Entity<Order>().HasQueryFilter(o => o.TenantId == _currentTenantId);

💡 Tip: Use IHttpContextAccessor to inject current tenant ID into repositories without passing it manually everywhere.

 

Q25. What are the multi-tenancy strategies and their trade-offs?

Strategy 1 — Shared Database, Shared Schema:

• All tenants share same tables. TenantId column on every table.

• Pros: Cheapest, easiest to maintain, one deployment.

• Cons: Risk of data leaks if TenantId filter missed; harder compliance (GDPR).

Strategy 2 — Shared Database, Separate Schema:

• Same DB, but each tenant has their own schema (tenant1.Orders, tenant2.Orders).

• Pros: Better isolation, schema-level security.

• Cons: Complex migrations (run per tenant); schema proliferation.

Strategy 3 — Separate Database per Tenant:

• Each tenant has their own database.

• Pros: Maximum isolation, easy backup/restore per tenant, compliance-friendly.

• Cons: Expensive (resource per tenant), complex connection management.

// Connection string resolved per tenant at runtime

var connStr = _tenantConfig[tenantId].ConnectionString;

💡 Tip: For financial/ERP systems with strict data isolation requirements, Separate Database is safest. For SaaS with many small tenants, Shared DB + TenantId is most cost-effective.

 

Q26. How do you resolve the current tenant in middleware?

// 1. Create ITenantService

public interface ITenantService { string GetCurrentTenantId(); }

public class TenantService : ITenantService {

private readonly IHttpContextAccessor _httpContext;

public string GetCurrentTenantId() {

// From subdomain

var host = _httpContext.HttpContext.Request.Host.Host;

return host.Split('.')[0]; // "tenant1" from "tenant1.app.com"

// OR from JWT claim:

// return _httpContext.HttpContext.User.FindFirst("tenantId")?.Value;

}

}

// 2. Register as Scoped

services.AddScoped<ITenantService, TenantService>();

services.AddHttpContextAccessor();

// 3. Inject into DbContext or Repository

public class AppDbContext : DbContext {

private readonly ITenantService _tenantService;

// Apply global query filter using current tenant

}

💡 Tip: Scoped lifetime for ITenantService ensures a fresh tenant resolution per HTTP request.

 

Section 6: Frontend — JS / jQuery / HTML5 / CSS3

 

Q27. What is the difference between == and === in JavaScript?

== (Abstract Equality — with type coercion):

Converts both values to the same type before comparing.

0 == false   // true  (false coerced to 0)

"" == false  // true

null == undefined // true

1 == "1"    // true  (string coerced to number)

=== (Strict Equality — no type coercion):

Checks both value AND type. No conversion.

0 === false  // false (different types)

1 === "1"   // false

null === undefined // false

1 === 1     // true

💡 Tip: Always use === in production code. == can cause subtle bugs due to unexpected type coercion. ESLint's eqeqeq rule enforces this.

 

Q28. Explain event delegation in jQuery/JavaScript.

Event delegation attaches a single event listener to a parent element instead of many listeners on individual child elements. It uses event bubbling — events bubble up from child to parent.

Without delegation (bad for dynamic elements):

// Won't work for dynamically added rows

$("tr.data-row").click(function() { ... });

With delegation (works for dynamic elements):

// Attach to static parent, delegate to dynamic children

$("#orderTable").on("click", "tr.data-row", function() { ... });

Benefits:

• Works for dynamically added elements (AJAX-loaded rows, etc.).

• Better performance — one listener instead of hundreds.

• Less memory usage.

💡 Tip: In your ERP grids where rows are added dynamically (PickList lines, SO lines), always use event delegation on the table/container.

 

Q29. What is the difference between Promise, async/await, and callbacks?

Callbacks (oldest, callback hell):

getData(function(data) {

processData(data, function(result) {

saveData(result, function() { /* done */ }); // deeply nested

});

});

Promises (ES6 — chainable):

getData()

.then(data => processData(data))

.then(result => saveData(result))

.catch(err => console.error(err));

Async/Await (ES2017 — cleanest, built on Promises):

async function process() {

try {

const data = await getData();

const result = await processData(data);

await saveData(result);

} catch(err) { console.error(err); }

}

💡 Tip: Always prefer async/await in modern code. It looks synchronous, is easier to read, and error handling with try/catch is natural.

 

Q30. How does Bootstrap grid work? What is flexbox vs grid in CSS?

Bootstrap Grid (12-column system):

• Container → Row → Columns. Columns must add up to 12.

<div class="container">

<div class="row">

<div class="col-md-8">Main Content</div>   <!-- 8/12 -->

<div class="col-md-4">Sidebar</div>        <!-- 4/12 -->

</div>

</div>

• Breakpoints: xs, sm, md, lg, xl, xxl.

CSS Flexbox (1-dimensional — row OR column):

• Best for: nav bars, card rows, aligning items in a line.

display: flex; justify-content: space-between; align-items: center;

CSS Grid (2-dimensional — rows AND columns):

• Best for: full page layouts, complex dashboards.

display: grid; grid-template-columns: 1fr 2fr 1fr; gap: 16px;

💡 Tip: Bootstrap 5 itself uses Flexbox internally. Use Grid when you need precise 2D layouts; Flexbox for 1D component alignment.

 

Q31. What are CSS specificity rules?

Specificity determines which CSS rule wins when multiple rules target the same element.

Specificity Hierarchy (highest to lowest):

1. Inline styles: style="color: red" → specificity: 1,0,0,0

2. ID selectors: #header → specificity: 0,1,0,0

3. Class, pseudo-class, attribute: .btn, :hover, [type] → 0,0,1,0

4. Element, pseudo-element: div, h1, ::before → 0,0,0,1

/* Which color wins for <p class="text" id="main"> ? */

p { color: black; }           /* 0,0,0,1 */

.text { color: blue; }        /* 0,0,1,0 — wins over p */

#main { color: green; }       /* 0,1,0,0 — wins over .text */

p#main { color: red; }        /* 0,1,0,1 — higher than #main alone */

!important overrides everything (use sparingly).

💡 Tip: Avoid !important. Keep specificity low and consistent. Use BEM naming (.block__element--modifier) to minimize specificity conflicts.

 

Section 7: ReactJS & Vue.js

 

Q32. What is the Virtual DOM and how does React reconcile changes?

Virtual DOM:

A lightweight JavaScript representation of the real DOM. React keeps a virtual copy of the UI in memory.

Reconciliation Process (Diffing Algorithm):

1. State/props change → React creates a new Virtual DOM tree.

2. React diffs the new tree against the previous Virtual DOM (reconciliation).

3. Identifies minimal set of changes (what actually changed).

4. Updates only those specific real DOM nodes (batched updates).

Why this matters:

• Direct DOM manipulation is slow. React batches and minimizes DOM touches.

• Gives illusion of full re-render with performance of surgical updates.

Key prop in lists:

<ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>

key helps React identify which items changed/moved/removed in lists.

💡 Tip: Without proper key props, React may re-render entire lists instead of only changed items — significant performance issue.

 

Q33. Explain useEffect — what are the dependency array options?

useEffect runs side effects after render (data fetching, subscriptions, DOM manipulation).

No dependency array — runs after EVERY render:

useEffect(() => { console.log('runs every render'); });

Empty array [] — runs ONCE after initial mount:

useEffect(() => { fetchData(); }, []); // like componentDidMount

With dependencies — runs when any dependency changes:

useEffect(() => { fetchOrders(customerId); }, [customerId]);

// Runs on mount AND whenever customerId changes

Cleanup function — runs before next effect or unmount:

useEffect(() => {

const subscription = subscribe(data);

return () => subscription.unsubscribe(); // cleanup

}, [data]);

💡 Tip: Always include all variables used inside useEffect in the dependency array. Use the eslint-plugin-react-hooks to catch missing dependencies.

 

Q34. What is the difference between controlled and uncontrolled components?

Controlled Component — React state is the source of truth:

• Input value is always driven by state. Every keystroke updates state.

const [name, setName] = useState('');

<input value={name} onChange={e => setName(e.target.value)} />

• Pros: Full control over validation, formatting, submission.

• Cons: More verbose.

Uncontrolled Component — DOM is the source of truth:

• Input manages its own state. Read value via ref when needed.

const inputRef = useRef();

<input ref={inputRef} defaultValue="initial" />

// Read value: inputRef.current.value

• Pros: Simpler for basic forms. Works like traditional HTML forms.

• Cons: Harder to validate/transform in real-time.

💡 Tip: Use controlled components for most forms — they work well with validation libraries like React Hook Form or Formik.

 

Q35. In Vue.js, what is the difference between computed and watch?

computed — Derived reactive data (like a calculated field):

• Returns a value based on other reactive data. Cached — only re-evaluates when dependencies change.

computed: {

fullName() {

return this.firstName + ' ' + this.lastName; // cached until firstName/lastName changes

}

}

• Use for: any value derived from state (totals, filtered lists, formatted dates).

watch — Imperative side effects when data changes:

• Runs code when a specific data property changes. For async operations or external side effects.

watch: {

customerId(newVal, oldVal) {

this.fetchOrders(newVal); // async call when customerId changes

}

}

• Use for: API calls, form validation triggers, localStorage sync.

Rule of thumb:

• Need a value? → computed.

• Need to DO something? → watch.

 

Q36. How do you manage state in a large React app?

1. Local State (useState) — for component-specific state:

const [isOpen, setIsOpen] = useState(false);

2. Context API — for moderate shared state (theme, user, language):

const UserContext = createContext();

<UserContext.Provider value={currentUser}>

<App /> // all children can access currentUser

</UserContext.Provider>

3. Redux — for complex global state with time-travel debugging:

• Centralized store. Actions → Reducers → State.

• Good for: large apps, complex state logic, many components sharing state.

4. Zustand (modern, lightweight alternative to Redux):

const useStore = create(set => ({

orders: [],

addOrder: (order) => set(state => ({ orders: [...state.orders, order] }))

}));

Decision Guide:

• Simple form state → useState.

• Auth/theme → Context API.

• Complex app-wide state → Redux or Zustand.

💡 Tip: Don't over-engineer. Start with useState + Context. Add Redux/Zustand only when prop drilling becomes painful.

 

Section 8: SQL / MSSQL

 

Q37. What is the difference between INNER JOIN, LEFT JOIN, and CROSS JOIN?

INNER JOIN — Returns only matching rows from both tables:

SELECT o.Id, c.Name FROM Orders o

INNER JOIN Customers c ON o.CustomerId = c.Id

-- Only orders that HAVE a matching customer

LEFT JOIN (LEFT OUTER JOIN) — Returns ALL rows from left table, NULLs for non-matching right:

SELECT o.Id, c.Name FROM Orders o

LEFT JOIN Customers c ON o.CustomerId = c.Id

-- All orders, even those without a customer (c.Name = NULL)

RIGHT JOIN — Opposite of LEFT JOIN. All rows from right table.

FULL OUTER JOIN — All rows from both tables, NULLs where no match.

CROSS JOIN — Cartesian product. Every row from table A × every row from table B:

SELECT * FROM Colors CROSS JOIN Sizes

-- 5 colors × 3 sizes = 15 combinations

💡 Tip: In ERP reports, LEFT JOIN is most common — you want all sales orders even if some data is incomplete.

 

Q38. What are clustered vs non-clustered indexes?

Clustered Index:

• Physically sorts and stores the table data rows in order of the index key.

• Only ONE clustered index per table (the data IS the index).

• Usually the Primary Key.

• CODE:CREATE CLUSTERED INDEX IX_Orders_Id ON Orders(Id)

• Retrieval by PK is fastest — data is physically ordered.

Non-Clustered Index:

• Separate structure from table data. Contains index key + pointer to actual row.

• Multiple non-clustered indexes allowed per table.

• CODE:CREATE NONCLUSTERED INDEX IX_Orders_CustomerId ON Orders(CustomerId)

• After finding rows in index, SQL Server does a bookmark lookup to get other columns.

When to add non-clustered indexes:

• Columns frequently in WHERE, JOIN ON, ORDER BY.

• Foreign key columns (CustomerId, PlantCode, etc.).

💡 Tip: Too many indexes slow down INSERT/UPDATE/DELETE (indexes must be maintained). Add indexes based on query profiler evidence, not guesswork.

 

Q39. How do you optimize a slow query?

Step-by-step approach:

1. Use SET STATISTICS TIME, IO ON and Execution Plan (CTRL+M in SSMS).

2. Look for Table Scans → add appropriate indexes.

3. Look for Key Lookups → add INCLUDE columns to the index.

4. Avoid SELECT * — only fetch needed columns.

5. Avoid functions on indexed columns in WHERE clause:

-- BAD (index not used):

WHERE YEAR(OrderDate) = 2024

-- GOOD (index used):

WHERE OrderDate >= '2024-01-01' AND OrderDate < '2025-01-01'

6. Use EXISTS instead of COUNT for existence checks.

7. Avoid N+1 — use JOINs instead of nested queries in loops.

8. Use pagination (OFFSET/FETCH) for large result sets.

9. Consider indexed views for frequently aggregated data.

💡 Tip: In your ERP, PickList queries filtering by Plant + DateRange are candidates for a composite index on (PlantCode, CreatedDate).

 

Q40. What is a CTE and when would you use it over a subquery?

CTE (Common Table Expression) — a named temporary result set defined with WITH:

WITH RecentOrders AS (

SELECT CustomerId, SUM(Amount) AS Total

FROM Orders

WHERE OrderDate >= DATEADD(MONTH, -3, GETDATE())

GROUP BY CustomerId

)

SELECT c.Name, r.Total

FROM Customers c

JOIN RecentOrders r ON c.Id = r.CustomerId

WHERE r.Total > 10000;

CTE vs Subquery:

• Readability: CTEs are more readable, especially for complex multi-step logic.

• Reusability: A CTE can be referenced multiple times in the query; subqueries cannot.

• Recursive: CTEs support recursive queries (hierarchical data — org charts, BOM).

-- Recursive CTE for Bill of Materials

WITH BOM_CTE AS (

SELECT ComponentId, ParentId, 0 AS Level FROM BOM WHERE ParentId IS NULL

UNION ALL

SELECT b.ComponentId, b.ParentId, c.Level + 1

FROM BOM b JOIN BOM_CTE c ON b.ParentId = c.ComponentId

)

💡 Tip: Use CTEs for readability and recursion. Use subqueries for simple one-off filters.

 

Q41. Explain transactions, ACID properties, and isolation levels.

ACID Properties:

• Atomicity: All operations succeed or all fail (all or nothing).

• Consistency: Database moves from one valid state to another.

• Isolation: Concurrent transactions don't interfere with each other.

• Durability: Committed data survives system failures.

BEGIN TRANSACTION

UPDATE Accounts SET Balance = Balance - 1000 WHERE Id = 1

UPDATE Accounts SET Balance = Balance + 1000 WHERE Id = 2

IF @@ERROR = 0 COMMIT ELSE ROLLBACK

Isolation Levels (trade-off: consistency vs concurrency):

• Read Uncommitted: Can read dirty (uncommitted) data. Fastest, least safe.

• Read Committed (default in SQL Server): Only reads committed data.

• Repeatable Read: Prevents non-repeatable reads. Holds shared locks.

• Serializable: Highest isolation. Prevents phantom reads. Slowest.

• Snapshot: Reads data as of transaction start. No locking — uses row versioning.

💡 Tip: For ERP financial operations (stock movements, billing), use at least Read Committed with explicit transactions. Consider Snapshot Isolation to reduce blocking.

 

Section 9: Security Best Practices

 

Q42. How do you prevent SQL Injection in .NET?

SQL Injection happens when user input is concatenated directly into SQL strings.

BAD — Vulnerable to injection:

string sql = "SELECT * FROM Users WHERE Name = '" + name + "'";

// If name = ' OR '1'='1 → returns ALL users!

Fix 1 — Parameterized Queries (ADO.NET):

SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Name = @Name", conn);

cmd.Parameters.AddWithValue("@Name", name); // safe, name treated as data

Fix 2 — Entity Framework (safe by default):

var user = db.Users.Where(u => u.Name == name).FirstOrDefault();

// EF automatically parameterizes all queries

Fix 3 — Stored Procedures with parameters:

EXEC sp_GetUser @Name = 'inputValue' -- safe

Additional defenses:

• Input validation and allowlisting.

• Least privilege DB accounts (no DROP/CREATE permissions for app user).

• Web Application Firewall (WAF).

💡 Tip: Entity Framework is safe by default. Only raw SQL methods like FromSqlRaw() need careful parameterization.

 

Q43. What is CSRF and how do you protect against it in ASP.NET?

CSRF (Cross-Site Request Forgery):

An attacker tricks an authenticated user into making unintended requests to your site (e.g., transfer money, change password).

How it works:

1. User is logged into bank.com (session cookie saved).

2. User visits evil.com which has: <img src='bank.com/transfer?amount=1000'>

3. Browser automatically sends the bank.com session cookie with the request!

Protection in ASP.NET MVC — Anti-Forgery Token:

// In View

@using (Html.BeginForm()) {

@Html.AntiForgeryToken() // hidden field with unique token

}

// In Controller

[ValidateAntiForgeryToken]

public ActionResult Save(OrderViewModel model) { ... }

In ASP.NET Core:

services.AddAntiforgery();

// Automatically applied to Razor Pages. For API, use SameSite cookies.

For APIs — use SameSite=Strict cookies and check Origin/Referer headers.

💡 Tip: CSRF only applies to cookie-based auth. JWT in Authorization header is immune to CSRF (browser doesn't auto-send headers).

 

Q44. How does JWT authentication work in .NET Core?

JWT (JSON Web Token) Structure: Header.Payload.Signature

• Header: algorithm (HS256, RS256).

• Payload: claims (userId, role, tenantId, expiry).

• Signature: ensures token hasn't been tampered with.

Flow:

1. User logs in → server validates credentials.

2. Server creates JWT signed with secret key → returns to client.

3. Client stores JWT (localStorage or httpOnly cookie).

4. Client sends JWT in header: Authorization: Bearer <token>.

5. Server validates signature + expiry on each request.

// Generate JWT

var token = new JwtSecurityToken(

issuer: "myapp", audience: "myapp",

claims: new[] { new Claim(ClaimTypes.Name, user.Name) },

expires: DateTime.Now.AddHours(1),

signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

// Validate JWT in Startup

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

.AddJwtBearer(opt => { opt.TokenValidationParameters = new TokenValidationParameters { ... }; });

💡 Tip: Always validate: Issuer, Audience, Lifetime, and Signature. Store the signing key in Azure Key Vault or environment variables — never in code.

 

Q45. What is CORS and how do you configure it in Web API?

CORS (Cross-Origin Resource Sharing):

Browser security mechanism that blocks JavaScript from making requests to a different domain than the page was loaded from.

Example: React app on http://localhost:3000 calling API on http://localhost:5000 → CORS error!

How CORS works:

Browser sends OPTIONS preflight request. Server responds with allowed origins/methods/headers.

Configuration in ASP.NET Core:

// In Program.cs

builder.Services.AddCors(opt => {

opt.AddPolicy("AllowReactApp", policy => {

policy.WithOrigins("http://localhost:3000", "https://myapp.com")

.AllowAnyMethod()

.AllowAnyHeader()

.AllowCredentials(); // if using cookies

});

});

app.UseCors("AllowReactApp"); // must be before UseAuthorization

Development shortcut (never in production):

policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); // insecure!

💡 Tip: Never use AllowAnyOrigin() in production. Always whitelist specific origins.

 

Section 10: Git / TFS / CI-CD

 

Q46. What is the difference between git merge and git rebase?

git merge — Combines two branches, creates a merge commit:

git checkout main

git merge feature/order-module

• Preserves complete history. Shows when branches diverged and merged.

• Creates a merge commit (non-linear history).

• Safe for shared/public branches.

git rebase — Moves commits to a new base, rewrites history:

git checkout feature/order-module

git rebase main

• Takes your feature commits and replays them on top of main.

• Creates a linear, cleaner history (no merge commits).

• DANGER: Rewrites commit hashes — never rebase public/shared branches.

When to use:

• Merge: integrating completed features into main, public branches.

• Rebase: cleaning up local feature branch before creating a PR.

💡 Tip: Golden rule — never rebase commits that have been pushed to a shared remote. Use merge for shared work, rebase for local cleanup.

 

Q47. How do you resolve merge conflicts in Git?

Steps to resolve conflicts:

1. Attempt merge: CODE:git merge feature-branch

2. Git marks conflicts in files with conflict markers:

<<<<<<< HEAD (your branch)

var x = GetOrderByPlant(plant);

=======

var x = GetOrderByRegion(region);

>>>>>>> feature-branch

3. Edit the file to keep the correct code (remove conflict markers).

4. Stage the resolved file: CODE:git add Controllers/OrderController.cs

5. Complete the merge: CODE:git commit

Tools for easier conflict resolution:

• VS Code: built-in merge editor with Accept Current/Incoming/Both buttons.

• Visual Studio: built-in Team Explorer merge tool.

• KDiff3, Beyond Compare: dedicated diff tools.

Aborting a merge gone wrong:

git merge --abort  // returns to pre-merge state

💡 Tip: Prevent conflicts by rebasing your feature branch on main frequently (keep it up to date). Small, frequent PRs have fewer conflicts than long-lived branches.

 

Q48. What is a CI/CD pipeline? What tools have you used?

CI (Continuous Integration):

Every code push automatically triggers: build + unit tests + code analysis.

Goal: Catch integration errors early, before they reach production.

CD (Continuous Deployment/Delivery):

After CI passes, automatically deploy to staging or production.

• Continuous Delivery: Auto-deploy to staging, manual approval for production.

• Continuous Deployment: Fully automated to production.

Typical .NET CI/CD Pipeline (Azure DevOps):

trigger: [main, develop]

stages:

- Build: dotnet restore → dotnet build → dotnet test

- Code Analysis: SonarQube scan

- Publish: dotnet publish → create artifact

- Deploy to Dev: auto

- Deploy to UAT: auto after Dev tests pass

- Deploy to Production: manual approval gate

Tools:

• Azure DevOps (Pipelines) — most common for .NET.

• Jenkins — open source, highly configurable.

• GitHub Actions — great for GitHub-hosted repos.

💡 Tip: For your ERP, even a basic CI that builds and runs unit tests on every commit prevents regression bugs significantly.

 

Q49. What is the difference between TFS and Git-based workflows?

TFS / TFVC (Team Foundation Version Control):

• Centralized version control. One central server holds all history.

• Developers check out files (lock-based), make changes, check in.

• Branching is expensive — full copy of the codebase.

• History stored on server; must be online to view history.

• Older model, still used in many enterprise/legacy shops.

Git (Distributed):

• Every developer has full local repository with complete history.

• Work offline, commit locally, push when ready.

• Branching is cheap and fast — branches are just pointers.

• Merge/PR workflow: feature branch → PR → code review → merge to main.

• Industry standard for modern development.

Migration:

• Azure DevOps supports both TFVC and Git repos.

• You can migrate TFVC history to Git using git-tfs tool.

💡 Tip: If your organization is still on TFS/TFVC, advocate for migrating to Git — it enables modern PR workflows, better branching strategies, and works with GitHub/Azure DevOps.

 

Section 11: Testing

 

Q50. What is the difference between Unit Testing, Integration Testing, and E2E Testing?

Unit Testing:

• Tests a single unit (method/class) in isolation. All dependencies mocked.

• Fast, no DB, no network. Run thousands in seconds.

[Fact]

public void Calculate_Discount_Returns_Correct_Price() {

var svc = new PriceService();

var result = svc.ApplyDiscount(100m, 0.10m);

Assert.Equal(90m, result);

}

Integration Testing:

• Tests how multiple components work together (controller + service + DB).

• Uses real DB (or in-memory), real HTTP.

// ASP.NET Core: WebApplicationFactory for integration tests

var client = new WebApplicationFactory<Program>().CreateClient();

var response = await client.GetAsync("/api/orders");

End-to-End (E2E) Testing:

• Tests full user flows through the actual UI (browser automation).

• Tools: Playwright, Selenium, Cypress.

• Slowest but most realistic.

Test Pyramid:

• Many unit tests (fast, cheap) → fewer integration tests → very few E2E tests (slow, expensive).

💡 Tip: Aim for 80%+ unit test coverage on business logic. Integration tests for API endpoints. E2E for critical user journeys.

 

Q51. How do you mock dependencies in unit tests?

Mocking replaces real dependencies with fake implementations that you control.

Using Moq (most popular .NET mocking library):

using Moq;

using Xunit;

[Fact]

public void PlaceOrder_SendsConfirmationEmail() {

// Arrange — create mocks

var mockRepo = new Mock<IOrderRepository>();

var mockEmail = new Mock<IEmailService>();

mockRepo.Setup(r => r.Save(It.IsAny<Order>())).Returns(true);

var service = new OrderService(mockRepo.Object, mockEmail.Object);

// Act

service.PlaceOrder(new Order { Amount = 500 });

// Assert — verify email was called

mockEmail.Verify(e => e.Send(It.IsAny<string>()), Times.Once);

}

Other libraries:

• NSubstitute: cleaner syntax.

• FakeItEasy: simple, readable.

💡 Tip: Mock at the interface boundary. This is why DI + interfaces are critical — they make your code testable.

 

Q52. What is Test-Driven Development (TDD)?

TDD — Write tests BEFORE writing production code. Red-Green-Refactor cycle:

1. RED: Write a failing test for the feature you want.

[Fact]

public void ApplyDiscount_10Percent_Returns90() {

var svc = new PriceService(); // doesn't exist yet

Assert.Equal(90m, svc.ApplyDiscount(100m, 0.10m)); // FAILS

}

2. GREEN: Write the minimum code to make the test pass.

public decimal ApplyDiscount(decimal price, decimal rate) => price * (1 - rate);

3. REFACTOR: Clean up the code while keeping tests passing.

Benefits of TDD:

• Forces thinking about API design before implementation.

• Ensures all code is testable by design.

• Creates a safety net for refactoring.

• Documentation through tests — tests show intended behavior.

Challenges:

• Requires discipline. Slower initially but faster long-term.

• Harder to apply to UI or legacy code.

💡 Tip: You don't have to be 100% TDD. Even writing tests alongside code (not after) significantly improves quality.

 

Section 12: Agile / Scrum & Soft Skills

 

Q53. Describe your experience working in Scrum.

Scrum Framework — Key ceremonies:

• Sprint Planning: Team selects user stories from backlog, estimates effort (story points), commits to sprint goal.

• Daily Standup: 15-min sync — What did I do? What will I do? Any blockers?

• Sprint Review (Demo): Show completed work to stakeholders.

• Sprint Retrospective: What went well? What to improve? Action items for next sprint.

Typical Sprint workflow:

1. Product Owner prioritizes backlog.

2. Stories refined and estimated in grooming sessions.

3. Team pulls stories into 2-week sprint.

4. Developer picks story → creates feature branch → develops → creates PR → code review → merge.

5. QA tests in staging. Done = dev + test + documented + reviewed.

Story Point estimation techniques:

• Planning Poker: Team votes simultaneously to avoid anchoring bias.

• T-shirt sizing: S/M/L/XL for high-level estimates.

Sample answer for interviewers:

"I work in 2-week sprints using Azure DevOps boards. I participate in daily standups, sprint planning, and retrospectives. I create feature branches per story and use PRs for code review before merging to develop."

💡 Tip: Show you understand the WHY of Scrum — it's about transparency, inspection, and adaptation — not just ceremonies.

 

Q54. How do you prioritize tasks when working on multiple features simultaneously?

Framework — prioritization approach:

1. Urgency vs Importance (Eisenhower Matrix):

   • Urgent + Important → Do immediately (production bugs, security issues).

   • Not Urgent + Important → Schedule (feature development, refactoring).

   • Urgent + Not Important → Delegate if possible.

   • Not Urgent + Not Important → Eliminate.

2. Business impact first: Does this block a client go-live or revenue?

3. Dependencies: What is blocking other team members? Unblock them first.

4. Technical risk: Items with unknown complexity get timeboxed investigation.

Practical techniques:

• Use your sprint board — committed stories take priority over ad-hoc requests.

• Communicate proactively: if you can't meet a deadline, say so early.

• Don't context-switch too rapidly — finish one thing before starting another.

Sample answer:

"I first handle any production issues or blockers for teammates. Then I follow sprint commitments. For new ad-hoc requests, I discuss with my lead whether they should enter the next sprint or be prioritized now based on business impact."

💡 Tip: Show maturity — interviewers want to see you communicate proactively, not just silently juggle.

 

Q55. Tell me about a time you identified a critical bug before production.

STAR Format (Situation, Task, Action, Result):

Situation:

"During development of the STOReceipt module, I noticed that when batch sizes were large (e.g., 500+ items), the page would freeze and throw a serialization error."

Task:

"I needed to identify the root cause and fix it before the feature went live, as it would affect all large warehouse receipt operations."

Action:

"I investigated and found the MaxJsonLength property of the JSON serializer was set to the default 2MB, which was insufficient for large batch payloads. I increased the limit in the Web.config and additionally implemented server-side pagination on the data endpoint to prevent sending massive JSON payloads to the client. I also added a save-button double-submission guard to prevent duplicate records during slow responses."

Result:

"The fix was deployed and tested with batches of 1000+ items without issues. The improvement also reduced page load time for large batches by 60%. We caught this in UAT — before it reached production users."

💡 Tip: Use a real example from your work. Interviewers value candidates who proactively find bugs rather than waiting for QA or end users to report them.

💡 Tip: Structure EVERY behavioral answer with STAR — it shows clear thinking and communication.

 

Based on the job description (Senior .NET Full Stack Developer – C#, MVC, Web API, .NET Core, Entity Framework, LINQ, SQL Server, JavaScript/jQuery) , here are commonly asked Interview Program and Database Questions with Answers.

C# / Programming Questions

1. Difference between ref, out, and in parameters?

Answer:

  • ref → Variable must be initialized before passing.
  • out → Variable need not be initialized.
  • in → Read-only parameter.
void Test(ref int a, out int b, in int c)
{
b = 10;
}

2. Difference between String and StringBuilder?

Answer:

  • String is immutable.
  • StringBuilder is mutable and better for multiple string manipulations.
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" World");

3. What is LINQ?

Answer:
LINQ (Language Integrated Query) allows querying collections and databases.

var result = employees
.Where(x => x.Salary > 50000)
.OrderBy(x => x.Name);

4. Difference between IEnumerable and IQueryable?

Answer:

IEnumerableIQueryable
Works in memoryExecutes on database
Slower for large dataBetter performance
LINQ to ObjectsLINQ to Entities

5. What is Dependency Injection?

Answer:
A design pattern used to reduce tight coupling.

public class EmployeeService
{
private readonly IRepository _repo;

public EmployeeService(IRepository repo)
{
_repo = repo;
}
}

6. What are Extension Methods?

public static class MyExtension
{
public static bool IsEven(this int num)
{
return num % 2 == 0;
}
}

Usage:

int x = 10;
x.IsEven();

7. Explain SOLID Principles.

Answer:

  • S – Single Responsibility Principle
  • O – Open Closed Principle
  • L – Liskov Substitution Principle
  • I – Interface Segregation Principle
  • D – Dependency Inversion Principle

8. Difference between Abstract Class and Interface?

Abstract ClassInterface
Can have implementationContract only
Single inheritanceMultiple inheritance
Constructor allowedNo constructor

9. What is Async/Await?

public async Task<string> GetData()
{
return await httpClient.GetStringAsync(url);
}

Used for non-blocking operations.


10. Reverse a String Program

string str = "Hello";
char[] arr = str.ToCharArray();
Array.Reverse(arr);
Console.WriteLine(new string(arr));

11. Find Duplicate Numbers

int[] arr = {1,2,3,2,4,1};

var duplicates = arr
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key);

12. Find Second Highest Number

int[] arr = {10,20,50,40};

int secondHighest = arr
.Distinct()
.OrderByDescending(x => x)
.Skip(1)
.First();

ASP.NET MVC / Web API Questions

13. MVC Life Cycle

  1. Request received
  2. Routing
  3. Controller
  4. Action Method
  5. View Rendering
  6. Response

14. What is Routing?

Maps URL to controller action.

routes.MapRoute(
"Default",
"{controller}/{action}/{id}"
);

15. Difference between TempData, ViewData, ViewBag?

ViewDataViewBagTempData
DictionaryDynamicNext request
Current requestCurrent requestRedirect support

16. HTTP Verbs

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

17. What is REST API?

A stateless service using HTTP methods.

Example:

GET /api/employee
POST /api/employee
PUT /api/employee/1
DELETE /api/employee/1

Entity Framework Questions

18. What is Entity Framework?

ORM framework that maps database tables to C# classes.


19. Code First vs Database First

Code FirstDatabase First
Classes firstDatabase first
Migration supportGenerate model from DB

20. What is Migration?

Used to maintain database schema changes.

Add-Migration InitialCreate
Update-Database

21. What is Lazy Loading?

Related entities load when accessed.

employee.Department

loads automatically.


SQL Server Questions

22. Difference between DELETE, TRUNCATE, DROP

DELETETRUNCATEDROP
Removes rowsRemoves all rowsRemoves table
Can rollbackCan rollbackStructure removed
WHERE allowedNo WHEREN/A

23. Difference between Clustered and Non-Clustered Index

ClusteredNon-Clustered
Data physically sortedSeparate structure
One per tableMultiple allowed

24. Find Duplicate Records

SELECT EmployeeCode,
COUNT(*)
FROM Employee
GROUP BY EmployeeCode
HAVING COUNT(*) > 1;

25. Second Highest Salary

SELECT MAX(Salary)
FROM Employee
WHERE Salary <
(
SELECT MAX(Salary)
FROM Employee
);

26. ROW_NUMBER vs RANK vs DENSE_RANK

SELECT *,
ROW_NUMBER() OVER(ORDER BY Salary DESC),
RANK() OVER(ORDER BY Salary DESC),
DENSE_RANK() OVER(ORDER BY Salary DESC)
FROM Employee;

27. Difference between CTE and Temp Table

CTETemp Table
Temporary result setPhysical object in tempdb
Single query scopeMultiple query scope

28. Find Employees Joined in Last 30 Days

SELECT *
FROM Employee
WHERE JoiningDate >= DATEADD(DAY,-30,GETDATE());

29. Explain ACID Properties

  • Atomicity
  • Consistency
  • Isolation
  • Durability

30. Performance Tuning Questions

What will you check if query is slow?

Answer:

  1. Execution Plan
  2. Missing Indexes
  3. Table Scan
  4. Statistics
  5. Joins
  6. CTE/Union usage
  7. Parameter Sniffing
  8. Blocking/Deadlocks

31. Difference between UNION and UNION ALL

SELECT Name FROM Employee
UNION
SELECT Name FROM Customer;
  • UNION removes duplicates.
  • UNION ALL keeps duplicates and is faster.

32. How to find blocking sessions?

EXEC sp_who2;

or

SELECT *
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;

These questions cover most areas mentioned in the .NET Full Stack requirement document, including C#, MVC, Web API, Entity Framework, LINQ, SQL Server, JavaScript, and .NET Core.



String Programs

Reverse String Without Built-in Function

string str = "Hello";
string rev = "";

for(int i = str.Length - 1; i >= 0; i--)
{
rev += str[i];
}

Console.WriteLine(rev);

Check Palindrome

string str = "madam";

string rev = new string(str.Reverse().ToArray());

Console.WriteLine(str == rev ? "Palindrome" : "Not Palindrome");

Count Vowels

string str = "Interview";

int count = str.Count(c => "aeiouAEIOU".Contains(c));

Console.WriteLine(count);

Find Duplicate Characters

string str = "programming";

var result = str.GroupBy(x => x)
.Where(x => x.Count() > 1);

foreach(var item in result)
{
Console.WriteLine(item.Key);
}

Array Programs

Largest Number

int[] arr = {10,20,30,50,40};

int max = arr[0];

foreach(int num in arr)
{
if(num > max)
max = num;
}

Console.WriteLine(max);

Second Largest Number

int[] arr = {10,20,30,50,40};

int second = arr.Distinct()
.OrderByDescending(x => x)
.Skip(1)
.First();

Console.WriteLine(second);

Missing Number

int[] arr = {1,2,3,5};

int n = 5;

int total = n * (n + 1) / 2;

int sum = arr.Sum();

Console.WriteLine(total - sum);

Remove Duplicates

int[] arr = {1,2,2,3,4,4,5};

var result = arr.Distinct();

foreach(var item in result)
{
Console.WriteLine(item);
}

Find Odd and Even Numbers

int[] arr = {1,2,3,4,5,6};

var even = arr.Where(x => x % 2 == 0);

var odd = arr.Where(x => x % 2 != 0);

Number Programs

Prime Number

int n = 17;
bool isPrime = true;

for(int i = 2; i <= Math.Sqrt(n); i++)
{
if(n % i == 0)
{
isPrime = false;
break;
}
}

Console.WriteLine(isPrime);

Factorial

int n = 5;
int fact = 1;

for(int i = 1; i <= n; i++)
{
fact *= i;
}

Console.WriteLine(fact);

Fibonacci Series

int a = 0, b = 1;

for(int i = 0; i < 10; i++)
{
Console.Write(a + " ");

int temp = a + b;

a = b;
b = temp;
}

Armstrong Number

int num = 153;

int temp = num;
int sum = 0;

while(temp > 0)
{
int rem = temp % 10;

sum += rem * rem * rem;

temp /= 10;
}

Console.WriteLine(sum == num);

LINQ Programs

Employees Salary Greater Than 50000

var result = employees
.Where(x => x.Salary > 50000)
.ToList();

Group By Department

var result = employees
.GroupBy(x => x.Department);

Highest Salary Employee

var emp = employees
.OrderByDescending(x => x.Salary)
.FirstOrDefault();

Top 3 Highest Salaries

var top3 = employees
.OrderByDescending(x => x.Salary)
.Take(3);

Collection Programs

Dictionary Example

Dictionary<int,string> dict =
new Dictionary<int,string>();

dict.Add(1,"Anil");
dict.Add(2,"Rahul");

Count Word Occurrences

string str = "apple mango apple banana mango";

var result = str.Split(' ')
.GroupBy(x => x)
.ToDictionary(x => x.Key,
x => x.Count());

Frequently Asked Practical Interview Programs

Swap Two Numbers Without Third Variable

int a = 10;
int b = 20;

a = a + b;
b = a - b;
a = a - b;

Find First Non-Repeated Character

string str = "swiss";

char result = str.GroupBy(x => x)
.Where(x => x.Count() == 1)
.Select(x => x.Key)
.First();

Console.WriteLine(result);

Check Anagram

string s1 = "listen";
string s2 = "silent";

bool result =
String.Concat(s1.OrderBy(x => x))
==
String.Concat(s2.OrderBy(x => x));

Console.WriteLine(result);

Reverse Words in Sentence

string str = "I Love Dot Net";

var result = string.Join(" ",
str.Split(' ')
.Reverse());

Console.WriteLine(result);

FizzBuzz (Very Common)

for(int i = 1; i <= 100; i++)
{
if(i % 3 == 0 && i % 5 == 0)
Console.WriteLine("FizzBuzz");
else if(i % 3 == 0)
Console.WriteLine("Fizz");
else if(i % 5 == 0)
Console.WriteLine("Buzz");
else
Console.WriteLine(i);
}

These are the programs most commonly asked in C#, .NET, MVC, Web API, and senior developer interviews because they test logic, LINQ, collections, and coding fundamentals.



1. Second Highest Salary

Employee Table

EmpIDNameSalary
1Anil50000
2Rahul70000
3Amit90000
4Mohit80000

Query

SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary <
(
SELECT MAX(Salary)
FROM Employee
);

Output

SecondHighestSalary
80000

2. Find Duplicate Records

Employee Table

Query

SELECT Email,
COUNT(*) AS Total
FROM Employee
GROUP BY Email
HAVING COUNT(*) > 1;

Output

EmailTotal
a@test.com2

3. ROW_NUMBER()

Query

SELECT Name,
Salary,
ROW_NUMBER() OVER(ORDER BY Salary DESC) AS RowNo
FROM Employee;

Output

NameSalaryRowNo
Amit900001
Mohit800002
Rahul700003
Anil500004

4. RANK()

Data

NameSalary
A90000
B80000
C80000
D70000

Query

SELECT Name,
Salary,
RANK() OVER(ORDER BY Salary DESC) AS RankNo
FROM Employee;

Output

NameSalaryRankNo
A900001
B800002
C800002
D700004

5. DENSE_RANK()

Query

SELECT Name,
Salary,
DENSE_RANK() OVER(ORDER BY Salary DESC) AS RankNo
FROM Employee;

Output

NameSalaryRankNo
A900001
B800002
C800002
D700003

6. Employees Joined Last 30 Days

Query

SELECT *
FROM Employee
WHERE JoiningDate >= DATEADD(DAY,-30,GETDATE());

Example Output

EmpIDNameJoiningDate
5Vivek2026-06-01
6Rohit2026-06-10

7. Difference Between WHERE and HAVING

Query

SELECT DepartmentID,
COUNT(*) TotalEmployees
FROM Employee
GROUP BY DepartmentID
HAVING COUNT(*) > 5;

Output

DepartmentIDTotalEmployees
108
207

WHERE filters rows before grouping.

HAVING filters groups after grouping.


8. Find Nth Highest Salary (3rd Highest)

Query

SELECT Salary
FROM
(
SELECT Salary,
DENSE_RANK() OVER(ORDER BY Salary DESC) RankNo
FROM Employee
) A
WHERE RankNo = 3;

Output

Salary
70000

9. Remove Duplicates

Table

IDName
1Anil
2Anil
3Rahul

Query

WITH CTE AS
(
SELECT *,
ROW_NUMBER() OVER
(
PARTITION BY Name
ORDER BY ID
) RN
FROM Employee
)
DELETE
FROM CTE
WHERE RN > 1;

Output

IDName
1Anil
3Rahul

10. Self Join (Manager-Employee)

Employee Table

EmpIDNameManagerID
1CEONULL
2Anil1
3Rahul1

Query

SELECT E.Name EmployeeName,
M.Name ManagerName
FROM Employee E
LEFT JOIN Employee M
ON E.ManagerID = M.EmpID;

Output

EmployeeNameManagerName
CEONULL
AnilCEO
RahulCEO

11. Running Total

Query

SELECT EmpID,
Salary,
SUM(Salary) OVER
(
ORDER BY EmpID
) RunningTotal
FROM Employee;

Output

EmpIDSalaryRunningTotal
110001000
220003000
330006000

12. Pivot Example

Data

MonthSales
Jan100
Feb200
Mar300

Query

SELECT *
FROM
(
SELECT Month,
Sales
FROM SalesData
) A
PIVOT
(
SUM(Sales)
FOR Month IN ([Jan],[Feb],[Mar])
) P;

Output

JanFebMar
100200300

13. CTE Output

WITH EmployeeCTE AS
(
SELECT *
FROM Employee
WHERE Salary > 50000
)
SELECT *
FROM EmployeeCTE;

Output

EmpIDNameSalary
2Rahul70000
3Amit90000

14. Find Top 2 Salaries Department Wise

WITH CTE AS
(
SELECT *,
DENSE_RANK() OVER
(
PARTITION BY DepartmentID
ORDER BY Salary DESC
) RN
FROM Employee
)
SELECT *
FROM CTE
WHERE RN <= 2;

Very Common Interview Question.


15. DELETE vs TRUNCATE Output

DELETE FROM Employee;

Output:

  • Rows deleted
  • Identity remains
TRUNCATE TABLE Employee;

Output:

  • All rows removed
  • Identity resets

Comments

Popular posts from this blog

SQL interview questions

Show Toaster message Simple example in HTML

How to Write "M Squared" (M²) in C#