C# .Net Core Interview Questions for Freshers and Experienced Developers

 

C#, .NetFramework, .Net Core interview Questions


For Angular and SQL Interview Questions, click here...!

1. IOC (Inversion of Control) Container in .NET Core

The IOC container in .NET Core is responsible for managing object creation and their dependencies. It's used for Dependency Injection (DI), making it easy to manage lifecycles (transient, scoped, singleton).


Example of registering a service:


public void ConfigureServices(IServiceCollection services)

{

    services.AddScoped<IMyService, MyService>();  // DI registration

}

2. Configure and ConfigureServices - When to Use What

ConfigureServices: Used to register services with the dependency injection container. Typically includes services like database context, authentication, and MVC.

Configure: Used to define the middleware pipeline (how requests are processed).

Example:


public void ConfigureServices(IServiceCollection services)

{

    services.AddControllers();

    services.AddDbContext<MyDbContext>();

}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();

    }

    app.UseRouting();

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

}

3. IActionResult

IActionResult is an interface that represents different HTTP responses like Ok(), NotFound(), Redirect(), etc., allowing a controller to return various types of results.


Example:


public IActionResult GetEmployee(int id)

{

    if (id <= 0)

    {

        return BadRequest("Invalid ID");

    }

    var employee = _service.GetEmployee(id);

    if (employee == null)

    {

        return NotFound();

    }

    return Ok(employee);

}

4. Why .NET Core?

Cross-platform: .NET Core runs on Windows, Linux, and macOS.

High performance: ASP.NET Core provides better performance than .NET Framework.

Modular architecture: Allows adding only the libraries needed for your application.

Open-source: .NET Core is open-source, making it highly adaptable by the community.

Cloud-ready: Optimized for modern cloud environments like Azure.

5. WebHostBuilder

The WebHostBuilder is used to set up the web server and middleware pipeline in .NET Core. It is responsible for configuring the application’s hosting environment.


Example:


public class Program

{

    public static void Main(string[] args)

    {

        CreateHostBuilder(args).Build().Run();

    }


    public static IHostBuilder CreateHostBuilder(string[] args) =>

        Host.CreateDefaultBuilder(args)

            .ConfigureWebHostDefaults(webBuilder =>

            {

                webBuilder.UseStartup<Startup>();

            });

}

6. RedirectToAction

This is used to redirect to another action method in the same or different controller.


public IActionResult RedirectToHome()

{

    return RedirectToAction("Index", "Home");

}

7. Transient and Scoped

Transient: Services are created each time they are requested.

Scoped: Services are created once per request.

Example of both in ConfigureServices:


public void ConfigureServices(IServiceCollection services)

{

    services.AddTransient<ITransientService, TransientService>();

    services.AddScoped<IScopedService, ScopedService>();

}

Practical difference:


Transient: Every time you inject a transient service, you get a new instance.

Scoped: During an HTTP request, the same instance is used for all services requiring it.

8. What is Middleware?

Middleware is software that handles HTTP requests and responses. It sits in the pipeline and can either pass the request to the next middleware or handle it.


Example:


public void Configure(IApplicationBuilder app)

{

    app.Use(async (context, next) =>

    {

        // Before request processing

        await next.Invoke();

        // After request processing

    });

}

9. Enable and Disable Middleware

You can enable or disable middleware in the Configure method. Middleware runs in the order you add it.


Example of disabling middleware based on the environment:


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();  // Enable in development

    }

}

10. Sequence of Filters

In ASP.NET Core, filters execute in the following order:


Authorization filters

Resource filters

Action filters

Exception filters

Result filters

11. Sequence of appsettings and Environment Data Files

appsettings.json is the base configuration file.

appsettings.{Environment}.json (e.g., appsettings.Development.json) overrides values for specific environments.

Values from appsettings.Development.json override appsettings.json when running in Development.

Example:


var builder = new ConfigurationBuilder()

    .AddJsonFile("appsettings.json")

    .AddJsonFile($"appsettings.{env.EnvironmentName}.json");

12. Practical Difference Between Transient and Scoped (with Example)

Transient: New instance every time.

Scoped: One instance per HTTP request.

Example:


public class MyController : Controller

{

    private readonly ITransientService _transientService;

    private readonly IScopedService _scopedService;


    public MyController(ITransientService transientService, IScopedService scopedService)

    {

        _transientService = transientService;

        _scopedService = scopedService;

    }


    public IActionResult Index()

    {

        _transientService.DoWork();  // New instance each time

        _scopedService.DoWork();     // Same instance during this request

        return View();

    }

}


1. Static and Singleton Class Difference
Static Class: Contains only static members, can’t be instantiated, and the instance is created only once.
Singleton Class: Allows only one instance to be created, but unlike static classes, it can implement interfaces, and the instance can be lazily loaded.
Example:

public class Singleton
{
    private static Singleton _instance = null;
    private Singleton() { }
    
    public static Singleton GetInstance()
    {
        if (_instance == null)
        {
            _instance = new Singleton();
        }
        return _instance;
    }
}
2. Program to Add Diagonal of a Matrix
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int diagonalSum = 0;
for (int i = 0; i < matrix.GetLength(0); i++)
{
    diagonalSum += matrix[i, i];
}
Console.WriteLine($"Sum of diagonal: {diagonalSum}");
3. Program to Find Index of First Non-Repeating Character in a String
public static int FirstNonRepeatingChar(string s)
{
    for (int i = 0; i < s.Length; i++)
    {
        if (s.LastIndexOf(s[i]) == s.IndexOf(s[i]))
        {
            return i;
        }
    }
    return -1; // No non-repeating character
}
4. Explicit Interface Implementation
Used when a class implements multiple interfaces with conflicting methods.

interface IA
{
    void Display();
}

interface IB
{
    void Display();
}

public class Test : IA, IB
{
    void IA.Display()
    {
        Console.WriteLine("IA Display");
    }

    void IB.Display()
    {
        Console.WriteLine("IB Display");
    }
}
5. Liskov Substitution Principle (LSP) Example
The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Example:

public class Bird
{
    public virtual void Fly() { }
}

public class Sparrow : Bird { }
public class Ostrich : Bird
{
    public override void Fly()
    {
        throw new NotImplementedException(); // Ostrich can't fly, violating LSP
    }
}
6. CICD (Continuous Integration & Continuous Deployment) Experience
CICD automates the process of software integration and deployment. It includes automated testing, building, and deploying applications. Tools like Jenkins, GitLab CI, Azure DevOps, and Docker are commonly used.

7. LINQ - Left Join and GroupBy
Left Join: Matches all elements in the left sequence, even if no elements are found in the right sequence.
var leftJoin = from e in Employees
               join d in Departments on e.DeptID equals d.DeptID into ed
               from dept in ed.DefaultIfEmpty()
               select new { e.Name, dept?.DeptName };
GroupBy: Groups elements by a key.
var groupBy = Employees.GroupBy(e => e.DeptID)
                       .Select(g => new { DeptID = g.Key, Count = g.Count() });
8. How to Create a Singleton Class
public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    private Singleton() { }
    public static Singleton Instance
    {
        get { return instance; }
    }
}
9. RedirectToAction
This is used in ASP.NET MVC to redirect the user to a different action method.

public IActionResult RedirectToHome()
{
    return RedirectToAction("Index", "Home");
}
10. Dispose vs. Finalize
Dispose: Implemented using IDisposable and used to manually free up resources.
Finalize: Automatically called by the garbage collector before the object is destroyed.
Example:

public class Resource : IDisposable
{
    public void Dispose()
    {
        // Clean up code
    }

    ~Resource()
    {
        Dispose();
    }
}
11. What is Assembly?
An assembly is a compiled code library used in .NET applications. Assemblies contain one or more managed code files and metadata. They are either DLL (dynamic link library) or EXE files.

12. Why Use Delegate?
Delegates allow methods to be passed as parameters. They support callbacks and event handling.

public delegate void MyDelegate(string message);
public void ShowMessage(string msg)
{
    Console.WriteLine(msg);
}
13. Multicast Delegate
A Multicast Delegate can point to multiple methods, and all are invoked in sequence.

public delegate void MyDelegate(string message);

public void Method1(string message) { Console.WriteLine("Method1: " + message); }
public void Method2(string message) { Console.WriteLine("Method2: " + message); }

MyDelegate del = Method1;
del += Method2;
del("Hello");
14. If Return in Both Catch and Finally
If there is a return statement in both catch and finally, the value in the finally block will override the value in the catch block.

15. LINQ for Employee Hierarchy
To get a hierarchical structure (e.g., manager and employee):

var hierarchy = Employees.GroupJoin(Employees,
    e => e.ManagerID,
    m => m.EmpID,
    (e, subordinates) => new { Employee = e, Subordinates = subordinates });
16. Design the Parking Lot System
A parking lot system design should include the following classes:

ParkingLot: Manages parking spaces and entry/exit points.
ParkingSpot: Represents individual parking spots.
Vehicle: Represents a vehicle with properties like size, plate number, etc.
Ticket: Issued when a vehicle enters and exits the lot.
17. Abstract and Interface Practical Use
Abstract Class: Use when you want to provide some common functionality but allow derived classes to implement additional features.
Interface: Use when you want to define a contract that multiple classes must follow.
Example:

public abstract class Animal
{
    public abstract void Speak();
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Bark");
    }
}

public interface IAnimal
{
    void Speak();
}

public class Cat : IAnimal
{
    public void Speak()
    {
        Console.WriteLine("Meow");
    }
}
18. Caching in Web API with Load Balancer
To implement caching in a web API behind a load balancer, you typically use distributed caching (e.g., Redis or SQL Server cache) to ensure all instances have access to the same cache.

Example using Redis:

public void ConfigureServices(IServiceCollection services)
{
    services.AddStackExchangeRedisCache(options =>
    {
        options.Configuration = "localhost:6379";
        options.InstanceName = "SampleInstance";
    });
}


1. Global Variable in C#
In C#, global variables don’t exist as they do in other languages. However, you can simulate them using static fields or properties inside a static class.

public static class Globals
{
    public static int GlobalVariable = 10;
}

// Access it anywhere:
int value = Globals.GlobalVariable;
2. Binding in C#
Binding refers to associating a method call to a method definition. There are two types:

Early Binding (Static Binding): Happens at compile-time.
Late Binding (Dynamic Binding): Happens at runtime using reflection or dynamic objects.
3. Factory Pattern
The Factory Pattern is used to create objects without exposing the creation logic to the client. It relies on a factory method to create objects based on the input.

Example:

public interface ICar
{
    void Drive();
}

public class BMW : ICar
{
    public void Drive() { Console.WriteLine("Driving BMW"); }
}

public class CarFactory
{
    public static ICar GetCar(string carType)
    {
        if (carType == "BMW") return new BMW();
        throw new ArgumentException("Invalid car type");
    }
}

ICar car = CarFactory.GetCar("BMW");
car.Drive();
4. Validation Web API Design for Different Banks
You can design an API with validation that varies per bank by using custom validation logic based on a bank identifier (bank code). Implementing interfaces per bank can help with modularity.

Example:

public interface IBankValidator
{
    bool ValidateTransaction(Transaction transaction);
}

public class HDFCValidator : IBankValidator
{
    public bool ValidateTransaction(Transaction transaction) { /* HDFC-specific logic */ }
}

public class BankValidatorFactory
{
    public static IBankValidator GetValidator(string bankCode)
    {
        if (bankCode == "HDFC") return new HDFCValidator();
        throw new Exception("Invalid bank code");
    }
}

// Usage in API
var validator = BankValidatorFactory.GetValidator(bankCode);
validator.ValidateTransaction(transaction);
5. LINQ
Language Integrated Query (LINQ) is used for querying collections in C#. Example:

var result = from emp in employees
             where emp.Age > 30
             select emp;
6. FirstOrDefault vs SingleOrDefault
FirstOrDefault: Returns the first element, or null if no element is found.
SingleOrDefault: Expects exactly one element; throws an exception if there’s more than one.
Example:

var firstEmployee = employees.FirstOrDefault(e => e.Age > 30); // Returns the first match or null
var singleEmployee = employees.SingleOrDefault(e => e.Id == 1); // Expects only one match
7. Interfaces and When to Use Them
Interfaces define a contract without implementation. They are useful when you need multiple classes to implement the same functionality but with different logic.

Example:

public interface IVehicle
{
    void Start();
}

public class Car : IVehicle
{
    public void Start() { Console.WriteLine("Car Starting"); }
}
8. Var vs Dynamic
var: Statically typed, resolved at compile time.
dynamic: Dynamically typed, resolved at runtime.
Example:

var x = "Hello"; // Statically typed
dynamic y = 10;  // Dynamically typed
9. Where OOP is Used in Your Project
You could mention how OOP principles like inheritance, polymorphism, and encapsulation are applied. For instance:

Encapsulation: By creating private fields and public properties.
Inheritance: For creating a base class for various components, e.g., Vehicle for cars and trucks.
10. Extension Methods
Extension methods allow adding new methods to existing types without modifying the type.

public static class StringExtensions
{
    public static string ToTitleCase(this string str)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }
}

// Usage:
string title = "hello world".ToTitleCase();
11. SOLID Principles
Single Responsibility Principle: A class should have one responsibility.
Open/Closed Principle: Classes should be open for extension but closed for modification.
Liskov Substitution Principle: Subtypes must be substitutable for their base types.
Interface Segregation Principle: Clients should not be forced to implement interfaces they don’t use.
Dependency Inversion Principle: High-level modules should not depend on low-level modules.
12. Memory Leaks in C#
Common causes of memory leaks include:

Unmanaged resources not being properly disposed.
Event handlers not unsubscribed. Use the Dispose() pattern and weak references to prevent memory leaks.
13. Abstract Class vs Interface
Abstract class: Can contain both abstract methods and implemented methods. Used when classes share common behavior.
Interface: Only contains method signatures, no implementation. Used for loose coupling.
Example:

public abstract class Animal
{
    public abstract void Speak();
    public void Eat() { Console.WriteLine("Eating"); }
}

public interface IAnimal
{
    void Speak();
}
14. AddTransient vs AddSingleton
AddTransient: New instance created every time the service is requested.
AddSingleton: Only one instance is created and shared across the application.
Example:

services.AddTransient<IMyService, MyService>();
services.AddSingleton<ILogger, Logger>();
15. Design Pattern
Factory Pattern: For creating objects.
Singleton Pattern: Restricts a class to one instance.
Observer Pattern: Used for event handling, notifying subscribers when changes occur.
16. Object Initialization
You can use object initializers to assign values to properties without calling a constructor.

var person = new Person { Name = "John", Age = 30 };
17. Interfaces Example
public interface IShape
{
    void Draw();
}

public class Circle : IShape
{
    public void Draw() { Console.WriteLine("Drawing Circle"); }
}
18. Method Overloading vs Overriding
Overloading: Same method name with different parameters.
Overriding: Redefining a method in a derived class.
Example:

public class Animal
{
    public virtual void Speak() { Console.WriteLine("Animal Speaking"); }
}

public class Dog : Animal
{
    public override void Speak() { Console.WriteLine("Dog Barking"); }
}
19. Reflection
Reflection is used to inspect metadata about assemblies, types, and methods at runtime.

Assembly assembly = Assembly.GetExecutingAssembly();
Type type = assembly.GetType("Namespace.ClassName");
20. Generics
Generics allow you to create a method or class that works with any data type.

public class GenericClass<T>
{
    public T Add(T a, T b) { return a; }
}
21. String Manipulation
String manipulation in C# includes operations like concatenation, trimming, replacement, etc.

Replace: Replace occurrences of a string.
string replaced = "Hello World".Replace("World", "C#");
22. Substring
Extracts a portion of the string.

string text = "Hello World";
string sub = text.Substring(0, 5); // Returns "Hello"

Array Manipulation
Example of adding elements, removing, and modifying:

int[] numbers = { 1, 2, 3, 4, 5 };
numbers[0] = 10; // Modify element at index 0
Array.Resize(ref numbers, 6); // Resize array
numbers[5] = 6; // Add new element
2. Dictionary Manipulation
Example of adding, accessing, and removing items from a dictionary:

Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "One");
dict[2] = "Two"; // Add or update element
dict.Remove(1);  // Remove element by key
string value = dict[2]; // Access element
3. Index of Uppercase and Lowercase
Find the index of uppercase and lowercase characters in a string:

string input = "HeLlo";
int firstUpper = input.IndexOf(c => char.IsUpper(c));
int firstLower = input.IndexOf(c => char.IsLower(c));
4. Distinct of String and Numbers
Using Distinct() to remove duplicates from strings and numbers:

string distinctString = new string("aaabbbccc".Distinct().ToArray());
var distinctNumbers = new List<int> { 1, 2, 2, 3, 3 }.Distinct();
5. Sorting of Numbers & Characters
Sort an array of numbers and characters:

int[] numbers = { 5, 2, 9, 1 };
Array.Sort(numbers); // Ascending sort

string chars = "dbca";
var sortedChars = new string(chars.OrderBy(c => c).ToArray());
6. Program for Repetition of Word or Character
Count the occurrences of a word or character in a string:

string sentence = "hello world hello";
var words = sentence.Split(' ');
var wordCount = words.GroupBy(w => w).ToDictionary(g => g.Key, g => g.Count());

string input = "hello";
var charCount = input.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
7. Program for Array Manipulation
Example of reversing an array:

int[] arr = { 1, 2, 3, 4 };
Array.Reverse(arr);
8. Date Format and Compare
Format and compare dates:

DateTime today = DateTime.Now;
string formattedDate = today.ToString("yyyy-MM-dd");

DateTime date1 = DateTime.Parse("2024-10-01");
DateTime date2 = DateTime.Now;
int result = DateTime.Compare(date1, date2); // -1, 0, or 1
9. StringBuilder
StringBuilder is used for efficient string manipulation:

StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.Append("World");
string result = sb.ToString();
10. Difference Between MVC Web API and Simple Web API
MVC Web API: Built for RESTful services and designed to work with HTTP protocols, and it follows MVC architectural pattern.
Simple Web API: May not follow MVC architecture strictly and can be designed for simpler service endpoints.
11. Why Use Static Class
Static classes are used when you want to provide global utility functions or shared data that doesn't require an instance.
public static class MathHelper
{
    public static int Add(int a, int b) => a + b;
}
12. Open/Closed Principle in Project
The Open/Closed Principle states that classes should be open for extension but closed for modification. You can mention extending functionality via interfaces, strategy patterns, or decorators.

13. Difference Between Thread and Process
Thread: The smallest unit of execution within a process.
Process: A running instance of a program. Each process has its memory space, but threads within the same process share memory.
14. Singleton
A singleton ensures only one instance of a class is created.

public class Singleton
{
    private static Singleton _instance;
    private Singleton() { }
    public static Singleton Instance => _instance ??= new Singleton();
}
15. Difference Between Single and Multithread
Single-threaded: Executes one thread at a time.
Multi-threaded: Executes multiple threads concurrently, improving efficiency.
16. How to Create an EDMX File (Steps)
In Visual Studio, right-click the project, select Add > New Item > Data > ADO.NET Entity Data Model.
Choose EF Designer from Database, select the database, and choose the tables to include.
17. AddSingleton and AddTransient Difference
AddSingleton: Creates one instance and reuses it.
AddTransient: Creates a new instance every time the service is requested.
18. Abstract Class and Interface Difference
Abstract Class: Can contain implementation; used for inheritance.
Interface: Only contains declarations; used for implementing multiple types.
19. Example of Interface in Child Class
public interface IShape
{
    void Draw();
}

public class Circle : IShape
{
    public void Draw() { Console.WriteLine("Drawing Circle"); }
}

IShape shape = new Circle();
shape.Draw();
20. Extension Method Example
public static class StringExtensions
{
    public static string ToTitleCase(this string input)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower());
    }
}

string title = "hello world".ToTitleCase();
21. Repetition Example Algorithm
Counting repetitions of elements:

string input = "aaabbbccc";
var count = input.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
22. Singleton Interface
You can have a singleton class that implements an interface:

public interface ILogger { void Log(string message); }

public class SingletonLogger : ILogger
{
    private static SingletonLogger _instance;
    private SingletonLogger() { }
    public static SingletonLogger Instance => _instance ??= new SingletonLogger();
    public void Log(string message) { Console.WriteLine(message); }
}
23. Ref, Out Parameter Example
ref: The variable must be initialized before being passed.
out: The variable does not need to be initialized before being passed.
Example:

void MethodRef(ref int x) { x += 10; }
void MethodOut(out int x) { x = 10; }

int a = 5;
MethodRef(ref a); // a becomes 15
int b;
MethodOut(out b); // b is assigned 10
24. Jagged Array
A jagged array is an array of arrays:

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
25. String Repetition Count
Counting the occurrences of a character in a string:

string input = "hello";
int count = input.Count(c => c == 'l'); // 2
26. 3 Types of Dependency Injection (DI)
Constructor Injection: Inject dependencies via constructor.
Property Injection: Inject dependencies via property.
Method Injection: Inject dependencies via method parameters.
27. Difference Between SQL & NoSQL
SQL: Relational, uses structured tables, follows ACID properties.
NoSQL: Non-relational, often schema-less, and suitable for distributed databases.
28. HashSet
A HashSet is a collection of unique elements:

HashSet<int> hashSet = new HashSet<int> { 1, 2, 3, 1 };
// Result: { 1, 2, 3 }


Difference Between Dictionary and Hashtable
Dictionary: Generic, type-safe, faster, no boxing/unboxing.
Hashtable: Non-generic, slower, requires boxing/unboxing.
Dictionary<int, string> dict = new Dictionary<int, string>();
Hashtable ht = new Hashtable();
2. AddSingleton & AddTransient
AddSingleton: Creates one instance for the entire application lifecycle.
AddTransient: Creates a new instance each time it is requested.
services.AddSingleton<IMyService, MyService>();
services.AddTransient<IMyService, MyService>();
3. Factory Pattern & Event-Based Pattern
Factory Pattern: Creates objects without specifying the exact class.
public interface IProduct { void Create(); }
public class ConcreteProduct : IProduct { public void Create() { } }
public class Factory
{
    public IProduct GetProduct() => new ConcreteProduct();
}
Event-Based Pattern: Allows objects to communicate using events.
public class Publisher
{
    public event EventHandler OnPublish;
    public void Publish() => OnPublish?.Invoke(this, EventArgs.Empty);
}
4. Data Annotation
Used for validating data in models.

public class Employee
{
    [Required]
    public string Name { get; set; }

    [Range(18, 65)]
    public int Age { get; set; }
}
5. String Reverse Program
string input = "Hello";
string reversed = new string(input.Reverse().ToArray());
6. Fluent API
Fluent API configures entities in Entity Framework through code, instead of attributes.

modelBuilder.Entity<Employee>()
    .HasKey(e => e.EmployeeId)
    .HasName("PK_EmployeeId");
7. Entity Code-First & Model-First Approach
Code-First: Write C# classes, then generate the database schema.
Model-First: Design the model in the visual designer, then generate the code and database.
8. Singleton Class Creation
public class Singleton
{
    private static Singleton instance = null;
    private Singleton() { }
    public static Singleton Instance => instance ??= new Singleton();
}
9. Factory Pattern
Creates objects based on a condition.

public class CarFactory
{
    public ICar GetCar(string carType)
    {
        if (carType == "Sedan") return new Sedan();
        else if (carType == "SUV") return new SUV();
        return null;
    }
}
10. Event-Based Pattern
Handles events in C#.

public class EventPublisher
{
    public event EventHandler DataReceived;
    public void OnDataReceived() => DataReceived?.Invoke(this, EventArgs.Empty);
}
11. Difference Between Web API and MVC API
Web API: Specializes in creating RESTful services.
MVC API: Based on the MVC pattern, designed for HTML pages and actions.
12. How to Disable Middleware
Remove middleware by not registering it in the pipeline, or using condition:

if (!env.IsDevelopment())
{
    app.UseMiddleware<SomeMiddleware>();
}
13. SelectMany in LINQ
Flattens a collection of collections.

var result = students.SelectMany(s => s.Subjects);
14. LINQ Fetch Third Highest Salary
var thirdHighestSalary = employees.OrderByDescending(e => e.Salary)
                                   .Skip(2)
                                   .First();
15. LINQ Query for Complex Variable
var query = from emp in employees
            where emp.Age > 30 && emp.Salary > 50000
            select emp;
16. Left Join in LINQ
var result = from e in employees
             join d in departments on e.DepartmentId equals d.Id into ed
             from dept in ed.DefaultIfEmpty()
             select new { e.Name, DepartmentName = dept?.Name };
17. Lambda Expression
Shorter syntax for methods and delegates.

Func<int, int> square = x => x * x;
18. Generics
Provides type safety while writing reusable code.

public class Repository<T> { public void Add(T item) { } }
19. Partial & Sealed Class
Partial: Allows splitting a class into multiple files.
Sealed: Prevents other classes from inheriting it.
20. Abstract Class and Interface
Abstract: Can contain both abstract and concrete methods.
Interface: Contains only abstract methods.
public abstract class Animal { public abstract void Sound(); }
public interface IVehicle { void Start(); }
21. Difference Between readonly and const
const: Compile-time constant, must be assigned when declared.
readonly: Runtime constant, can be assigned in the constructor.
const int MaxValue = 100;
readonly int MinValue;
22. GAC (Global Assembly Cache)
GAC is used to store shared assemblies globally in .NET.

23. Shared Assembly and Private Assembly
Shared Assembly: Stored in GAC, used by multiple applications.
Private Assembly: Stored in the application directory, used only by that application.
24. Encapsulation
Encapsulation hides the internal state of an object and exposes only necessary parts.

public class Employee
{
    private int _id;
    public int Id { get => _id; set => _id = value; }
}
25. Dynamic and Static Overloading
Static Overloading: Compile-time polymorphism with multiple method signatures.
Dynamic Overloading: Runtime-based method selection, not supported in C#.
26. Attribute
Used to add metadata to code.

[Obsolete("This method is deprecated")]
public void OldMethod() { }
27. Virtual Class or Method
Virtual Method: Can be overridden in derived classes.
public class BaseClass
{
    public virtual void Display() { Console.WriteLine("Base"); }
}
28. Dynamic - ExpandoObject
Dynamic type can hold any value, and ExpandoObject can add properties dynamically.

dynamic expando = new ExpandoObject();
expando.Name = "John";
29. SOLID Principles
S: Single Responsibility Principle.
O: Open/Closed Principle.
L: Liskov Substitution Principle.
I: Interface Segregation Principle.
D: Dependency Inversion Principle.
30. Design Patterns
Common design patterns include:

Singleton: Ensures a class has only one instance.
Factory: Creates objects without specifying the exact type.
Observer: Notifies multiple objects about changes.
Decorator: Adds behavior to objects dynamically.

Method Overriding
Overriding allows a subclass to provide a specific implementation of a method already defined in its parent class.

public class BaseClass
{
    public virtual void Show() => Console.WriteLine("Base Class");
}
public class DerivedClass : BaseClass
{
    public override void Show() => Console.WriteLine("Derived Class");
}
2. Static Class and Methods
Static Class: Can’t be instantiated. Used for utility or helper methods.

public static class MathOperations
{
    public static int Add(int a, int b) => a + b;
}
3. Inheritance
Allows a class to inherit methods and properties from another class.

public class Animal { public void Eat() { Console.WriteLine("Eating"); } }
public class Dog : Animal { public void Bark() { Console.WriteLine("Barking"); } }
4. Lock in Multi-threading
Used to ensure that one thread doesn't access critical sections of code while another thread is still executing it.

private static readonly object _lock = new object();
public void ThreadSafeMethod()
{
    lock (_lock)
    {
        // Critical section of code
    }
}
5. Process and Thread Difference
Process: An independent program running in its own memory space.
Thread: A unit of execution within a process.
6. Filters in ASP.NET MVC
Filters are attributes that execute code before or after certain stages in the request processing pipeline.

[Authorize] // Authorization Filter
public class HomeController : Controller
{
    public IActionResult Index() { }
}
7. Exception Handling
Using try-catch-finally to handle exceptions.

try { int result = 10 / 0; }
catch (DivideByZeroException ex) { Console.WriteLine("Error: " + ex.Message); }
finally { Console.WriteLine("Cleanup code here"); }
8. Extension Methods
Static methods that allow adding new functionalities to existing types without modifying them.

public static class StringExtensions
{
    public static bool IsPalindrome(this string str)
    {
        return str == new string(str.Reverse().ToArray());
    }
}
9. Palindrome Program

string input = "madam";
bool isPalindrome = input.SequenceEqual(input.Reverse());
10. Fibonacci Series Program

int n = 10, a = 0, b = 1;
Console.Write($"{a} {b} ");
for (int i = 2; i < n; i++)
{
    int temp = a + b;
    Console.Write(temp + " ");
    a = b;
    b = temp;
}
11. Searching Program (Linear Search)

int[] arr = { 1, 3, 5, 7 };
int key = 5;
int index = Array.FindIndex(arr, x => x == key);
12. Sorting Program (Bubble Sort)

int[] arr = { 5, 2, 9, 1 };
for (int i = 0; i < arr.Length - 1; i++)
    for (int j = 0; j < arr.Length - i - 1; j++)
        if (arr[j] > arr[j + 1])
            (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
13. File Handling in C#

using System.IO;
File.WriteAllText("file.txt", "Hello World");
string content = File.ReadAllText("file.txt");
14. CRUD Operations in ASP.NET Core
Create: Add data to the database.
Read: Fetch data.
Update: Modify data.
Delete: Remove data.

[HttpPost]
public IActionResult CreateEmployee(Employee employee) { /* Add to DB */ }
15. Armstrong Number Program

int number = 153, sum = 0, temp = number;
while (temp != 0)
{
    int digit = temp % 10;
    sum += Math.Pow(digit, 3);
    temp /= 10;
}
bool isArmstrong = sum == number;
16. PAN Number Validation

string pan = "ABCDE1234F";
bool isValid = Regex.IsMatch(pan, @"^[A-Z]{5}[0-9]{4}[A-Z]$");
17. Alphabet Count in a Sentence

string sentence = "Hello World";
int letterCount = sentence.Count(char.IsLetter);
18. Collection Types with Examples
List: Dynamic array
Dictionary: Key-value pairs

List<int> numbers = new List<int>() { 1, 2, 3 };
Dictionary<string, string> dict = new Dictionary<string, string> { {"Key1", "Value1"} };
19. Web API vs WCF
Web API: RESTful, lightweight, ideal for HTTP-based services.
WCF: Supports SOAP and other protocols, more complex.
20. Cross-Origin in Web API (CORS)
Used to allow or block requests from different domains.

services.AddCors(options => {
    options.AddPolicy("AllowAll", builder => {
        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
    });
});
21. Alias Naming
You can alias a namespace or a class to avoid conflicts.

using ProjectA = NamespaceA.ClassA;
22. Attribute Routing in Web API

[Route("api/employees/{id}")]
public IActionResult GetEmployee(int id) { /* Get employee by id */ }
23. Media Type Formatters in Web API
Handles converting data to specific formats like JSON or XML.
24. Web API Authentication and Authorization Flow
Use JWT Tokens or OAuth for securing API endpoints.
Authentication: Verifies user identity.
Authorization: Determines access levels based on roles.
25. OOP Concepts in C#
Encapsulation: Data hiding.
Inheritance: Reuse base class functionality.
Polymorphism: Multiple forms of a method (method overloading/overriding).
Abstraction: Hide complex implementation details.
26. Class vs Structure
Class: Reference type, supports inheritance, can be null.
Struct: Value type, no inheritance, cannot be null.
27. Object as Reference
When passed to a method, objects are passed by reference, allowing modification of original data.
28. Abstract Class vs Class
Abstract class is a base class that can't be instantiated and may contain abstract methods.
29. Polymorphism - Overloading & Overriding
Overloading: Multiple methods with the same name but different parameters.
Overriding: Derived class redefines the base class method.
30. Abstraction vs Encapsulation
Abstraction: Hides the implementation.
Encapsulation: Protects data by hiding it.
31. Abstract Class vs Interface
Abstract Class: Can have concrete methods.
Interface: Only has method declarations, no concrete implementation.
32. Implicit vs Explicit Interface Implementation

public interface ITest { void Show(); }
public class MyClass : ITest
{
    void ITest.Show() { } // Explicit implementation
}
33. Sealed Class & Method
Sealed Class: Prevents inheritance.
Sealed Method: Prevents overriding in derived classes.
34. ExpandoObject
Used to add properties dynamically at runtime.

dynamic obj = new ExpandoObject();
obj.Name = "John";
35. Static, Virtual & Override
Static: Method belongs to the class.
Virtual: Allows overriding in derived classes.
Override: Replaces base class implementation.
36. Dynamic vs Var
Var: Type is determined at compile-time.
Dynamic: Type is determined at runtime.

Nullable Types
Nullable types allow value types to be assigned null.

int? nullableInt = null;
if (nullableInt.HasValue)
{
    Console.WriteLine(nullableInt.Value);
}
else
{
    Console.WriteLine("No value assigned");
}

out and ref
out and ref are used to pass arguments by reference.

void ExampleOut(out int number)
{
    number = 10; // Must be assigned before method ends
}

void ExampleRef(ref int number)
{
    number += 10; // Can be used without assignment
}

int a;
ExampleOut(out a); // a is now 10

int b = 5;
ExampleRef(ref b); // b is now 15

const vs readonly
const is a compile-time constant, while readonly is a runtime constant.

public class Example
{
    public const int ConstValue = 10;
    public readonly int ReadOnlyValue;

    public Example(int value)
    {
        ReadOnlyValue = value; // Can only be assigned in constructor
    }
}

Multicast Delegates
Multicast delegates can point to multiple methods.

public delegate void Notify();

public class MulticastExample
{
    public static void Method1() => Console.WriteLine("Method1");
    public static void Method2() => Console.WriteLine("Method2");

    public static void Main()
    {
        Notify notify = Method1;
        notify += Method2;
        notify(); // Calls both Method1 and Method2
    }
}

Jagged Array
A jagged array is an array of arrays.

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

Singleton Implementation
Singleton ensures a class has only one instance.

public class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Delegate
A delegate is a type that represents references to methods.

public delegate void DisplayMessage(string message);

public class DelegateExample
{
    public static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }

    public static void Main()
    {
        DisplayMessage display = ShowMessage;
        display("Hello, World!");
    }
}

Boxing and Unboxing
Boxing converts a value type to an object type, and unboxing extracts the value type from the object.

int num = 123;
object boxed = num; // Boxing
int unboxed = (int)boxed; // Unboxing

throw vs throw ex
throw preserves the original stack trace, while throw ex resets it.

try
{
    // Some code
}
catch (Exception ex)
{
    throw; // Preserves stack trace
    // throw ex; // Resets stack trace
}

Can Multiple Catch Blocks Execute?
No, only the first matching catch block executes.

try
{
    // Some code
}
catch (ArgumentException ex)
{
    // Handle ArgumentException
}
catch (Exception ex)
{
    // Handle other exceptions
}

Serialization
Serialization converts an object to a format that can be stored or transmitted.

[Serializable]
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class SerializationExample
{
    public static void Main()
    {
        Person person = new Person { Name = "John", Age = 30 };
        IFormatter formatter = new BinaryFormatter();
        using (Stream stream = new FileStream("person.bin", FileMode.Create, FileAccess.Write))
        {
            formatter.Serialize(stream, person);
        }
    }
}

Dependency Injection
Dependency Injection is a design pattern for managing dependencies.

public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve() => Console.WriteLine("Service Called");
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start() => _service.Serve();
}

public class Program
{
    public static void Main()
    {
        IService service = new Service();
        Client client = new Client(service);
        client.Start();
    }
}

async and await
async and await are used for asynchronous programming.

public async Task<string> GetDataAsync()
{
    await Task.Delay(1000); // Simulate async work
    return "Data";
}

public async Task MainAsync()
{
    string data = await GetDataAsync();
    Console.WriteLine(data);
}

Constructor Multicasting
Constructor multicasting isn’t a standard term, but you might be referring to calling multiple constructors.

public class Example
{
    public Example() : this(0) { }

    public Example(int value)
    {
        Console.WriteLine(value);
    }
}

Reflection
Reflection allows inspection of metadata and dynamic invocation.

Type type = typeof(String);
MethodInfo method = type.GetMethod("Substring", new[] { typeof(int), typeof(int) });
string result = (string)method.Invoke("Hello, World!", new object[] { 7, 5 });
Console.WriteLine(result); // Output: World

Generics
Generics allow type-safe data structures.

public class GenericExample<T>
{
    private T data;

    public GenericExample(T value)
    {
        data = value;
    }

    public T GetData() => data;
}

public class Program
{
    public static void Main()
    {
        GenericExample<int> example = new GenericExample<int>(5);
        Console.WriteLine(example.GetData());
    }
}

Design Patterns
Commonly asked design patterns include Singleton, Factory, Observer, and Strategy.

// Example of Factory Pattern
public interface IProduct
{
    void DoWork();
}

public class ConcreteProduct : IProduct
{
    public void DoWork() => Console.WriteLine("ConcreteProduct is working");
}

public class Factory
{
    public IProduct CreateProduct() => new ConcreteProduct();
}

public class Program
{
    public static void Main()
    {
        Factory factory = new Factory();
        IProduct product = factory.CreateProduct();
        product.DoWork();
    }
}


View Encapsulation in Angular
View encapsulation determines whether the styles defined in a component affect the whole application or just the component itself.

TypeScript

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.Emulated // Options: Emulated, None, ShadowDom
})
export class AppComponent {}

Shadow Box in Angular
To apply a shadow box in Angular, you can use the box-shadow CSS property.

HTML

<div class="shadow-box">Content</div>

CSS

.shadow-box {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}

ViewChild and ViewChildren
ViewChild and ViewChildren are used to access child components or DOM elements.

TypeScript

import { Component, ViewChild, ViewChildren, QueryList, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '<p>Child Component</p>'
})
export class ChildComponent {}

@Component({
  selector: 'app-parent',
  template: `
    <app-child></app-child>
    <app-child></app-child>
  `
})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) singleChild: ChildComponent;
  @ViewChildren(ChildComponent) multipleChildren: QueryList<ChildComponent>;

  ngAfterViewInit() {
    console.log(this.singleChild);
    this.multipleChildren.forEach(child => console.log(child));
  }
}

SwitchMap
switchMap is an RxJS operator used to switch to a new observable.

TypeScript

import { Component } from '@angular/core';
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  template: '<p>Check console for output</p>'
})
export class AppComponent {
  ngOnInit() {
    of('Hello').pipe(
      switchMap(value => of(`${value} World`))
    ).subscribe(result => console.log(result)); // Output: Hello World
  }
}

HostListener
HostListener is used to listen to DOM events on the host element.

TypeScript

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<p>Click anywhere</p>'
})
export class AppComponent {
  @HostListener('document:click', ['$event'])
  onClick(event: Event) {
    console.log('Document clicked', event);
  }
}

ESLint
ESLint is a tool for identifying and fixing problems in JavaScript code.

# Install ESLint in an Angular project
ng add @angular-eslint/schematics

Event Loop
The event loop is a mechanism that handles asynchronous operations in JavaScript.

JavaScript

console.log('Start');

setTimeout(() => {
  console.log('Timeout');
}, 0);

console.log('End');

// Output: Start, End, Timeout

Callback Function
A callback function is a function passed into another function as an argument.

TypeScript

function fetchData(callback: (data: string) => void) {
  setTimeout(() => {
    callback('Data received');
  }, 1000);
}

fetchData(data => console.log(data)); // Output: Data received

package.json and package-lock.json
package.json contains metadata about the project and its dependencies, while package-lock.json locks the versions of dependencies.

JSON

// package.json
{
  "name": "example",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "^4.17.21"
  }
}

// package-lock.json
{
  "name": "example",
  "version": "1.0.0",
  "dependencies": {
    "lodash": {
      "version": "4.17.21",
      "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
      "integrity": "sha512-v2kDE7XGZ4k+..."
    }
  }
}

Multithreading in Node.js
Node.js uses worker threads for multithreading.

JavaScript

const { Worker } = require('worker_threads');

const worker = new Worker(`
  const { parentPort } = require('worker_threads');
  parentPort.postMessage('Hello from worker');
`, { eval: true });

worker.on('message', message => console.log(message)); // Output: Hello from worker

Without await in Node.js
Using promises without await.

JavaScript

function fetchData() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Data received');
    }, 1000);
  });
}

fetchData().then(data => console.log(data)); // Output: Data received

Callback, Import, Using
Using callback functions, importing modules, and using statements.

TypeScript

// Callback
function fetchData(callback: (data: string) => void) {
  setTimeout(() => {
    callback('Data received');
  }, 1000);
}

// Import
import { Component } from '@angular/core';

// Using
fetchData(data => console.log(data)); // Output: Data received

Authentication
Authentication is the process of verifying the identity of a user.

TypeScript

// Example of JWT Authentication in Angular
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private http: HttpClient) {}

  login(credentials: { username: string, password: string }): Observable<any> {
    return this.http.post('/api/auth/login', credentials);
  }
}

What is npm and package.json
npm is a package manager for JavaScript, and package.json is a file that contains metadata about the project and its dependencies.

JSON

// package.json
{
  "name": "example",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "^4.17.21"
  }
}

Which Compiler
TypeScript uses the TypeScript compiler (tsc).

# Install TypeScript
npm install -g typescript

# Compile TypeScript file
tsc example.ts

Why TypeScript in Angular
TypeScript provides static typing, which helps catch errors at compile time.

TypeScript

let message: string = 'Hello, TypeScript';
console.log(message);

Exception Handling in Stored Procedure
Handling exceptions in SQL stored procedures.

SQL

CREATE PROCEDURE ExampleProcedure
AS
BEGIN
  BEGIN TRY
    -- Your SQL code here
  END TRY
  BEGIN CATCH
    -- Handle error here
    PRINT ERROR_MESSAGE();
  END CATCH
END

Using TypeScript to JavaScript
Transpiling TypeScript to JavaScript.

TypeScript

// TypeScript
let message: string = 'Hello, TypeScript';
console.log(message);

// JavaScript (after transpiling)
var message = 'Hello, TypeScript';
console.log(message);

Authentication in C#
Example of authentication in C# using ASP.NET Core.


public class AuthController : ControllerBase
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AuthController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginModel model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);
        if (result.Succeeded)
        {
            return Ok();
        }
        return Unauthorized();
    }
}

Max Memory for Lambda
The maximum memory allocation for AWS Lambda is 10 GB.

Trigger Lambda without API Gateway
You can trigger AWS Lambda using S3 events, DynamoDB streams, SNS, SQS, and more.

How is Angular Loading
Angular uses a module loader to load modules dynamically.

Private Interface
Interfaces cannot be private in TypeScript.

Composition of Token
Tokens in authentication can include header, payload, and signature.

Abstract and Interface
Abstract classes can have implementations, interfaces cannot.

Sealed Class
A sealed class cannot be inherited.

Constant and Readonly
const is a compile-time constant, readonly is a runtime constant.

SOLID Principles
SOLID principles are a set of design principles for software development.

Ref and Out
ref and out are used to pass arguments by reference in C#.

Interface
An interface defines a contract that implementing classes must follow.

Cluster and Non-Cluster Index
Clustered index sorts the data, non-clustered index does not.

Views in SQL and ADO.NET
Views are virtual tables in SQL, ADO.NET is a data access technology.

Entity Framework
Entity Framework is an ORM for .NET.

Can We Declare Private Interface
No, interfaces cannot be private.

Main.ts in Angular
main.ts is the entry point of an Angular application.


Difference Between Structure and Class
Structs are value types, while classes are reference types.
Structs are stored on the stack, whereas classes are stored on the heap.
Structs cannot inherit from other structs or classes, but they can implement interfaces.
Classes support inheritance.
C#

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

class MyClass
{
    public int X;
    public int Y;
}

Abstract Class
An abstract class cannot be instantiated and is designed to be inherited by subclasses that implement its abstract methods.

C#

public abstract class Animal
{
    public abstract void MakeSound();
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

Sealed Class
A sealed class cannot be inherited.

C#

public sealed class SealedClass
{
    public void Display()
    {
        Console.WriteLine("This is a sealed class.");
    }
}

Static in C#
Static members belong to the type itself rather than to a specific object.

C#

public static class Utility
{
    public static void DisplayMessage(string message)
    {
        Console.WriteLine(message);
    }
}

Angular Component Lifecycle
Angular components have several lifecycle hooks:

TypeScript

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<p>Example Component</p>'
})
export class ExampleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}

Where to Declare Constants
Constants are declared using the const keyword and must be initialized at the time of declaration.

C#

public class Example
{
    public const int MaxValue = 100;
}

Child Module in Angular
Child modules are feature modules that are imported into the root module or other feature modules.

TypeScript

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from './child.component';

@NgModule({
  declarations: [ChildComponent],
  imports: [CommonModule]
})
export class ChildModule {}

Cluster Module in Angular
Cluster modules are not a standard Angular concept but can refer to modules that handle clustering logic, such as marker clustering in maps.

Docker
Docker is a platform for developing, shipping, and running applications in containers.

# Dockerfile example
FROM node:14
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
CMD ["node", "index.js"]

Jenkins
Jenkins is an open-source automation server used for continuous integration and continuous delivery (CI/CD).

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}

Sanitization in Angular
Sanitization in Angular is used to prevent security vulnerabilities like XSS attacks.

TypeScript

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-sanitizer',
  template: '<div [innerHtml]="safeHtml"></div>'
})
export class SanitizerComponent {
  safeHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {
    this.safeHtml = this.sanitizer.bypassSecurityTrustHtml('<p>Safe HTML</p>');
  }
}

Section and Article
<section> and <article> are HTML5 semantic elements used to structure content.

HTML

<section>
  <h1>Section Title</h1>
  <p>Section content...</p>
</section>

<article>
  <h2>Article Title</h2>
  <p>Article content...</p>
</article>

No Cache and Local Storage
Local storage is used to store data on the client side.

JavaScript

// Set item
localStorage.setItem('key', 'value');

// Get item
let value = localStorage.getItem('key');

Web Storage
Web storage includes localStorage and sessionStorage.

JavaScript

// localStorage persists until explicitly deleted
localStorage.setItem('key', 'value');

// sessionStorage persists only for the session
sessionStorage.setItem('key', 'value');

Web Worker
Web workers allow you to run scripts in background threads.

JavaScript

// worker.js
self.onmessage = function(e) {
  self.postMessage('Worker received: ' + e.data);
};

// main.js
let worker = new Worker('worker.js');
worker.onmessage = function(e) {
  console.log(e.data);
};
worker.postMessage('Hello, worker!');

Early Binding and Late Binding
Early binding refers to compile-time binding, while late binding refers to runtime binding.

Schematic Element in HTML
Schematic elements are not a standard HTML concept but could refer to custom elements or components.

ForChild
forChild is used in Angular routing to define child routes.

TypeScript

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      { path: 'child', component: ChildComponent }
    ]
  }
];

Lazy Loading
Lazy loading in Angular loads modules only when needed.

TypeScript

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

Iframe
An <iframe> is used to embed another HTML page within the current page.

HTML

<iframe src="https://example.com" width="600" height="400"></iframe>

Selector in CSS
Selectors are used to select HTML elements for styling.

CSS

/* Class selector */
.class-name {
  color: blue;
}

/* ID selector */
#id-name {
  color: red;
}

Global Selector
The global selector (*) selects all elements.

CSS

* {
  margin: 0;
  padding: 0;
}

End Tag Not Needed in HTML
Some HTML elements do not require end tags, like <img> and <br>.

HTML

<img src="image.jpg" alt="Image">
<br>

Responsive Application
Responsive design ensures that applications work on various screen sizes.

CSS

@media (max-width: 600px) {
  .container {
    flex-direction: column;
  }
}

Authentication Interceptor
An authentication interceptor in Angular intercepts HTTP requests to add authentication tokens.

TypeScript

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = 'your-auth-token';
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${authToken}`)
    });
    return next.handle(authReq);
  }
}

Angular Security
Angular provides built-in security features like sanitization and HTTP interceptors.

Session Management
Session management involves maintaining user sessions, often using cookies or tokens.

JSON Not Proper in Node.js Validate
Use a JSON schema validator like ajv to validate JSON.

JavaScript

const Ajv = require('ajv');
const ajv = new Ajv();

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['name', 'age']
};

const validate = ajv.compile(schema);
const data = { name: 'John', age: 30 };

if (validate(data)) {
  console.log('Valid!');
} else {
  console.log('Invalid:', validate.errors);
}

NoSQL vs DynamoDB
DynamoDB is a NoSQL database service provided by AWS.

Div and Span in Same Line
Use CSS to display <div> and <span> elements inline.

CSS

div, span {
  display: inline-block;
}

Concurrent 4 API
Use Promise.all to handle multiple API calls concurrently.

JavaScript

Promise.all([
  fetch('/api/endpoint1'),
  fetch('/api/endpoint2'),
  fetch('/api/endpoint3'),
  fetch('/api/endpoint4')
]).then(responses => {
  return Promise.all(responses.map(response => response.json()));
}).then(data => {
  console.log(data);
});

Promise.all
Promise.all waits for all promises to resolve.

JavaScript

Promise.all([promise1, promise2]).then(values => {
  console.log(values);
});

Node.js Run
Run a Node.js application using node.

node app.js

Difference Between Tuple and Dictionary
Tuples are ordered collections of elements, while dictionaries are key-value pairs.

Python

# Tuple
t = (1, 2, 3)

# Dictionary
d = {'key1': 'value1', 'key2': 'value2'}

Tuple
A tuple is an immutable, ordered collection of elements.

Python

t = (1, 2, 3)


Difference Between Interface and Abstract Class
Interface: Defines a contract with no implementation. Classes implementing the interface must provide the implementation.
Abstract Class: Can have both abstract methods (without implementation) and concrete methods (with implementation). Used when classes share a common base but also need to provide specific implementations.
C#

public interface IAnimal
{
    void MakeSound();
}

public abstract class Animal
{
    public abstract void MakeSound();
    public void Sleep()
    {
        Console.WriteLine("Sleeping");
    }
}

public class Dog : Animal, IAnimal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

Types of Constructors
Default Constructor: No parameters.
Parameterized Constructor: Takes parameters.
Copy Constructor: Initializes an object using another object of the same class.
Static Constructor: Initializes static members of the class.
Private Constructor: Prevents the class from being instantiated.
C#

public class Example
{
    public int X;
    public int Y;

    // Default Constructor
    public Example() { }

    // Parameterized Constructor
    public Example(int x, int y)
    {
        X = x;
        Y = y;
    }

    // Copy Constructor
    public Example(Example example)
    {
        X = example.X;
        Y = example.Y;
    }

    // Static Constructor
    static Example()
    {
        Console.WriteLine("Static Constructor");
    }

    // Private Constructor
    private Example(string message)
    {
        Console.WriteLine(message);
    }
}

Difference Between Normal and Static Constructor
Normal Constructor: Initializes instance members and is called when an instance of the class is created.
Static Constructor: Initializes static members and is called only once, before any instance is created or any static members are referenced.
C#

public class Demo
{
    public int InstanceValue;
    public static int StaticValue;

    // Normal Constructor
    public Demo()
    {
        InstanceValue = 10;
    }

    // Static Constructor
    static Demo()
    {
        StaticValue = 20;
    }
}

Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon.

C#

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Meow");
    }
}

public class Program
{
    public static void Main()
    {
        Animal myDog = new Dog();
        Animal myCat = new Cat();
        myDog.MakeSound(); // Output: Bark
        myCat.MakeSound(); // Output: Meow
    }
}

Overloading in TypeScript
Function overloading allows multiple function signatures for a single function implementation.

TypeScript

function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
    return a + b;
}

console.log(add(1, 2)); // Output: 3
console.log(add("Hello, ", "World!")); // Output: Hello, World!

Cancelled Promise
Promises in JavaScript cannot be directly cancelled, but you can use AbortController to cancel an asynchronous operation.

JavaScript

const controller = new AbortController();
const signal = controller.signal;

fetch('https://jsonplaceholder.typicode.com/todos/1', { signal })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => {
        if (err.name === 'AbortError') {
            console.log('Fetch aborted');
        } else {
            console.error('Fetch error:', err);
        }
    });

// Cancel the fetch request
controller.abort();

How Dependency Injection Works Internally
Dependency Injection (DI) in C# involves injecting dependencies into a class through its constructor, properties, or methods. The DI container manages the lifecycle and resolution of these dependencies.

C#

public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve() => Console.WriteLine("Service Called");
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start() => _service.Serve();
}

public class Program
{
    public static void Main()
    {
        var service = new Service();
        var client = new Client(service);
        client.Start();
    }
}

Project Architecture
Project architecture defines the structure and interaction of components within a software system. It includes layers like presentation, business logic, and data access.

Full-Text Search in SQL
Full-text search allows querying textual data in SQL databases using indexes.

SQL

CREATE FULLTEXT CATALOG MyCatalog;
CREATE FULLTEXT INDEX ON MyTable (MyColumn) KEY INDEX PK_MyTable;
SELECT * FROM MyTable WHERE CONTAINS(MyColumn, 'search term');

Static Constructor and Its Use
A static constructor initializes static members of a class and is called only once.

C#

public class Example
{
    static Example()
    {
        Console.WriteLine("Static Constructor Called");
    }
}

Can We Have Parameterized Static Constructor?
No, static constructors cannot have parameters.

Extension Method
Extension methods add new methods to existing types without modifying them.

C#

public static class StringExtensions
{
    public static string Reverse(this string str)
    {
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

public class Program
{
    public static void Main()
    {
        string example = "Hello";
        Console.WriteLine(example.Reverse()); // Output: olleH
    }
}

Caching in C#
Caching improves performance by storing frequently accessed data.

C#

public class CacheExample
{
    private static readonly MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());

    public void SetCache(string key, object value)
    {
        _cache.Set(key, value, TimeSpan.FromMinutes(10));
    }

    public object GetCache(string key)
    {
        return _cache.TryGetValue(key, out var value) ? value : null;
    }
}

LINQ
LINQ (Language Integrated Query) allows querying collections in a readable and concise manner.

C#

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

Hashtable and Dictionary Difference and Which is Faster
Hashtable: Non-generic, thread-safe for single writer and multiple readers.
Dictionary: Generic, not thread-safe, faster due to type safety.
C#

Hashtable hashtable = new Hashtable();
Dictionary<int, string> dictionary = new Dictionary<int, string>();

HashSet
A HashSet is a collection of unique elements.

C#

HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 };

Design Patterns
Common design patterns include Singleton, Factory, Observer, and Strategy.

Real-Time Scenario of Where to Use Interface and Abstract Classes
Interface: Use when multiple classes need to implement the same set of methods.
Abstract Class: Use when classes share common behavior but also have specific implementations.
Program: Do String Permutation and Split It into Equal Parts
C#

public static void Permute(string str, int l, int r)
{
    if (l == r)
        Console.WriteLine(str);
    else
    {
        for (int i = l; i <= r; i++)
        {
            str = Swap(str, l, i);
            Permute(str, l + 1, r);
            str = Swap(str, l, i);
        }
    }
}

public static string Swap(string a, int i, int j)
{
    char temp;
    char[] charArray = a.ToCharArray();
    temp = charArray[i];
    charArray[i] = charArray[j];
    charArray[j] = temp;
    return new string(charArray);
}

Program: Find Index of First Non-Repeating Character
C#

public static int FirstNonRepeatingChar(string s)
{
    var dict = new Dictionary<char, int>();
    foreach (var c in s)
    {
        if (dict.ContainsKey(c))
            dict[c]++;
        else
            dict[c] = 1;
    }
    for (int i = 0; i < s.Length; i++)
    {
        if (dict[s[i]] == 1)
            return i;
    }
    return -1;
}

Program: Find the Diagonal Sum of 3x3 Array
C#

public static int DiagonalSum(int[,] matrix)
{
    int sum = 0;
    for (int i = 0; i < 3; i++)
    {
        sum += matrix[i, i];
        sum += matrix[i, 2 - i];
    }
    return sum;
}


Duck Typing in Angular
Duck typing, or structural typing, is a concept where the type or class of an object is determined by its behavior (methods and properties) rather than its explicit type. In TypeScript, this means that if an object has all the required properties and methods, it can be used where that type is expected, regardless of its actual type.

TypeScript

interface Duck {
  quack(): void;
}

class Mallard {
  quack() {
    console.log("Quack!");
  }
}

let duck: Duck = new Mallard(); // This works because Mallard has a quack method
duck.quack(); // Output: Quack!

Difference Between SingleOrDefault and FirstOrDefault
SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty. Throws an exception if more than one element is found.
FirstOrDefault: Returns the first element of a sequence, or a default value if the sequence is empty.
C#

var numbers = new List<int> { 1, 2, 3 };

// SingleOrDefault
var single = numbers.SingleOrDefault(n => n == 2); // Returns 2
var singleNotFound = numbers.SingleOrDefault(n => n == 4); // Returns 0 (default for int)

// FirstOrDefault
var first = numbers.FirstOrDefault(); // Returns 1
var firstNotFound = new List<int>().FirstOrDefault(); // Returns 0 (default for int)

Difference Between Dependency Injection (DI) and Inversion of Control (IoC)
Inversion of Control (IoC): A design principle where the control of object creation and management is transferred from the application to a container or framework.
Dependency Injection (DI): A specific implementation of IoC where dependencies are injected into a class, rather than the class creating the dependencies itself.
How to Do Dependency Injection in Different Classes
Dependency Injection can be done using constructor injection, property injection, or method injection.

C#

public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve() => Console.WriteLine("Service Called");
}

public class Client
{
    private readonly IService _service;

    // Constructor Injection
    public Client(IService service)
    {
        _service = service;
    }

    public void Start() => _service.Serve();
}

// Usage
var service = new Service();
var client = new Client(service);
client.Start();

Difference Between Attributes and Properties
Attributes: Metadata added to code elements (classes, methods, properties) to provide additional information used by the compiler or runtime.
Properties: Members of a class that provide a flexible mechanism to read, write, or compute the value of a private field.
C#

[Serializable]
public class Example
{
    public string Name { get; set; }
}

Is .NET Core Only for Multi-Level Platform?
No, .NET Core is a cross-platform framework that runs on Windows, macOS, and Linux12.

Singleton Design Pattern
The Singleton pattern ensures a class has only one instance and provides a global point of access to it.

C#

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

How to Display Content in Angular
Use content projection with <ng-content> to display content in Angular components.

TypeScript

@Component({
  selector: 'app-card',
  template: '<div class="card"><ng-content></ng-content></div>'
})
export class CardComponent {}

// Usage
<app-card>
  <p>This is projected content</p>
</app-card>

Lazy Loading Concept & How It Works
Lazy loading in Angular loads modules only when needed, reducing the initial load time.

TypeScript

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

Storage of Memory in Call by Value and Call by Reference Type
Call by Value: Copies the actual value of an argument into the formal parameter of the function.
Call by Reference: Copies the reference to the memory location of an argument into the formal parameter.
C#

void CallByValue(int x)
{
    x = 100;
}

void CallByReference(ref int x)
{
    x = 100;
}

int a = 10;
CallByValue(a); // a remains 10
CallByReference(ref a); // a becomes 100

Project Insight
Project architecture typically includes layers like presentation, business logic, and data access.

Sealed Class
A sealed class cannot be inherited.

C#

public sealed class SealedClass
{
    public void Display() => Console.WriteLine("This is a sealed class.");
}

Abstract Class
An abstract class cannot be instantiated and is designed to be inherited by subclasses that implement its abstract methods.

C#

public abstract class Animal
{
    public abstract void MakeSound();
}

public class Dog : Animal
{
    public override void MakeSound() => Console.WriteLine("Bark");
}

Abstract / Interface Difference
Abstract Class: Can have both abstract and concrete methods.
Interface: Only defines methods and properties without implementation.
Authentication and Authorization in Angular Using JWT Token
Use Angular’s HTTP interceptors to add JWT tokens to requests.

TypeScript

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = 'your-auth-token';
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${authToken}`)
    });
    return next.handle(authReq);
  }
}

Authorization from Web API in .NET Core [Authorize Filter]
Use the [Authorize] attribute to secure Web API endpoints.

C#

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
    [HttpGet]
    public IActionResult GetSecureData()
    {
        return Ok("This is secure data");
    }
}

Polymorphism Example
Polymorphism allows methods to do different things based on the object it is acting upon.

C#

public class Animal
{
    public virtual void MakeSound() => Console.WriteLine("Animal sound");
}

public class Dog : Animal
{
    public override void MakeSound() => Console.WriteLine("Bark");
}

public class Cat : Animal
{
    public override void MakeSound() => Console.WriteLine("Meow");
}

public class Program
{
    public static void Main()
    {
        Animal myDog = new Dog();
        Animal myCat = new Cat();
        myDog.MakeSound(); // Output: Bark
        myCat.MakeSound(); // Output: Meow
    }
}

Can a Stored Procedure Be Called from a Function?
No, a stored procedure cannot be called from a function in SQL Server.

SQL - Sum of Salary with and Without Using SUM
Using SUM:

SQL

SELECT SUM(Salary) FROM Employees;

Without using SUM:

SQL

SELECT 
    (SELECT Salary FROM Employees WHERE EmployeeID = 1) +
    (SELECT Salary FROM Employees WHERE EmployeeID = 2) +
    (SELECT Salary FROM Employees WHERE EmployeeID = 3) AS TotalSalary;

Cursor - Code
A cursor in SQL Server is used to iterate through a result set row by row.

SQL

DECLARE @EmployeeID INT;
DECLARE EmployeeCursor CURSOR FOR
SELECT EmployeeID FROM Employees;

OPEN EmployeeCursor;
FETCH NEXT FROM EmployeeCursor INTO @EmployeeID;

WHILE @@FETCH_STATUS = 0
BEGIN
    -- Process each row
    FETCH NEXT FROM EmployeeCursor INTO @EmployeeID;
END;

CLOSE EmployeeCursor;
DEALLOCATE EmployeeCursor;

Angular Structure
Angular applications are structured into modules, components, services, and templates.

CLR - How It Works
The Common Language Runtime (CLR) is the virtual machine component of .NET that manages the execution of .NET programs.

Triangle * Print Program
C#

for (int i = 1; i <= 5; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write("*");
    }
    Console.WriteLine();
}

Show Manager ID with Employee Using Self Join
SQL

SELECT e.EmployeeID, e.EmployeeName, m.EmployeeName AS ManagerName
FROM Employees e
LEFT JOIN Employees m ON e.ManagerID = m.EmployeeID;

Promise / Observable Difference
Promise: Handles a single asynchronous event.
Observable: Handles a stream of asynchronous events.
TypeScript

// Promise
let promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Promise resolved'), 1000);
});

// Observable
let observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Observable emitted');
    observer.complete();
  }, 1000);
});


.NET Framework vs .NET Core
.NET Framework: Windows-only, mature, extensive libraries, used for desktop and web applications.
.NET Core: Cross-platform (Windows, macOS, Linux), modern, high performance, modular, used for cloud, IoT, and microservices.
Base Class & Child Class in Depth
A base class (parent) provides common functionality, while a child class (derived) inherits and extends it.


public class Animal
{
    public void Eat() => Console.WriteLine("Eating");
}

public class Dog : Animal
{
    public void Bark() => Console.WriteLine("Barking");
}

public class Program
{
    public static void Main()
    {
        Dog dog = new Dog();
        dog.Eat(); // Inherited method
        dog.Bark(); // Child class method
    }
}

Dependency Injection (DI) and How to Use It
DI is a design pattern that allows a class to receive its dependencies from an external source rather than creating them itself.


public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve() => Console.WriteLine("Service Called");
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start() => _service.Serve();
}

// Usage
var service = new Service();
var client = new Client(service);
client.Start();

Triggers in SQL
Triggers are special stored procedures that automatically execute in response to certain events on a table or view.

SQL

CREATE TRIGGER trgAfterInsert
ON Employees
AFTER INSERT
AS
BEGIN
    PRINT 'After Insert Trigger Fired'
END;

Delegates in C#
Delegates are type-safe function pointers used to pass methods as arguments.


public delegate void Notify(string message);

public class Program
{
    public static void Main()
    {
        Notify notify = ShowMessage;
        notify("Hello, World!");
    }

    public static void ShowMessage(string message)
    {
        Console.WriteLine(message);
    }
}

Delegates vs Events with Example
Delegates: Directly call methods.
Events: Encapsulate delegates, providing a way to notify subscribers.

public delegate void Notify();

public class EventPublisher
{
    public event Notify OnNotify;

    public void NotifySubscribers()
    {
        OnNotify?.Invoke();
    }
}

public class Subscriber
{
    public void Subscribe(EventPublisher publisher)
    {
        publisher.OnNotify += () => Console.WriteLine("Notified");
    }
}

Generics Explanation
Generics allow you to define classes, methods, and interfaces with a placeholder for the type.


public class GenericClass<T>
{
    private T data;

    public GenericClass(T value)
    {
        data = value;
    }

    public T GetData() => data;
}

Can Generics Be in Interfaces?
Yes, interfaces can be generic.


public interface IRepository<T>
{
    void Add(T item);
    T Get(int id);
}

How to Avoid Build Errors by Creating Constructors in Generics Class
Ensure the generic type has a parameterless constructor.


public class GenericClass<T> where T : new()
{
    private T data;

    public GenericClass()
    {
        data = new T();
    }
}

Value Type and Reference Type
Value Type: Stores data directly (e.g., int, struct).
Reference Type: Stores a reference to the data (e.g., class, string).

int valueType = 10; // Value type
string referenceType = "Hello"; // Reference type

Properties and Fields Difference
Fields: Variables declared directly in a class.
Properties: Provide a flexible mechanism to read, write, or compute the value of a private field.

public class Example
{
    private int field;

    public int Property { get; set; }
}

Can We Create Custom Value Types?
Yes, using struct.


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

Polymorphism of Class Concepts
Polymorphism allows methods to do different things based on the object it is acting upon.


public class Animal
{
    public virtual void MakeSound() => Console.WriteLine("Animal sound");
}

public class Dog : Animal
{
    public override void MakeSound() => Console.WriteLine("Bark");
}

Async Call and How It Works
Async methods allow for asynchronous programming, improving responsiveness.


public async Task<string> GetDataAsync()
{
    await Task.Delay(1000); // Simulate async work
    return "Data";
}

Async Call to DB Using Entity Framework
Use async and await with Entity Framework for database operations.


public async Task<List<Employee>> GetEmployeesAsync()
{
    using (var context = new MyDbContext())
    {
        return await context.Employees.ToListAsync();
    }
}

Entity Usage in Project
Entity Framework is an ORM that simplifies data access by mapping objects to database tables.

Project Insights - Detailed
Project architecture typically includes layers like presentation, business logic, and data access.

HTTP Methods
Common HTTP methods include GET, POST, PUT, DELETE, PATCH.

Configuration of Angular to API
Configure Angular to communicate with an API using HttpClient.

TypeScript

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('/api/data');
  }
}

Where Are Libraries Stored in Angular? Flow?
Libraries are stored in the node_modules folder. Angular uses a module system to manage dependencies.

GET / POST, Update and PATCH Difference - Web API
GET: Retrieve data.
POST: Create new data.
PUT: Update existing data.
PATCH: Partially update existing data.
Microservice Basic Architecture and Flow
Microservices architecture involves breaking down an application into smaller, independent services that communicate over HTTP.

AWS Flow in Application
AWS services like Lambda, S3, and DynamoDB can be used to build scalable applications.

Abstract Methods in Application
Abstract methods are declared in abstract classes and must be implemented by derived classes.

Release/Debug Process
Release builds are optimized for performance, while debug builds include additional debugging information.

Metadata Package
Metadata packages contain information about the structure and content of data.

HTTP Options in .NET Core
HTTP options in .NET Core include configuring middleware, routing, and services.

Idempotent - Which is Idempotent in HTTP Verbs
Idempotent HTTP methods include GET, PUT, DELETE, and OPTIONS, meaning multiple identical requests have the same effect as a single request.

Pure Virtual Class
In C#, the concept of a “pure virtual class” is not directly applicable as it is in C++. However, you can achieve similar functionality using abstract classes and methods. An abstract class in C# can have abstract methods that must be implemented by derived classes.


public abstract class Animal
{
    public abstract void MakeSound(); // Abstract method
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

Abstract Method
An abstract method is a method that is declared in an abstract class and does not have an implementation. Derived classes must provide an implementation for the abstract method.


public abstract class Shape
{
    public abstract double GetArea(); // Abstract method
}

public class Circle : Shape
{
    private double radius;

    public Circle(double radius)
    {
        this.radius = radius;
    }

    public override double GetArea()
    {
        return Math.PI * radius * radius;
    }
}

Dependency Injection (DI)
Dependency Injection is a design pattern used to implement IoC (Inversion of Control), allowing the creation of dependent objects outside of a class and providing those objects to a class in various ways.


public interface IService
{
    void Serve();
}

public class Service : IService
{
    public void Serve() => Console.WriteLine("Service Called");
}

public class Client
{
    private readonly IService _service;

    public Client(IService service)
    {
        _service = service;
    }

    public void Start() => _service.Serve();
}

// Usage
var service = new Service();
var client = new Client(service);
client.Start();

SOLID Principles
SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable:

Single Responsibility Principle (SRP): A class should have only one reason to change.
Open/Closed Principle (OCP): Software entities should be open for extension but closed for modification.
Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
Interface Segregation Principle (ISP): No client should be forced to depend on methods it does not use.
Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.
Open/Closed Principle (OCP) in Depth
The Open/Closed Principle states that software entities should be open for extension but closed for modification. This can be achieved using interfaces or abstract classes.


public interface IShape
{
    double CalculateArea();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double CalculateArea()
    {
        return Width * Height;
    }
}

public class AreaCalculator
{
    public double CalculateArea(IShape shape)
    {
        return shape.CalculateArea();
    }
}

Mixins in WebAPI / Angular
Mixins in TypeScript allow you to create reusable classes that can be combined to form new classes.

TypeScript

type Constructor<T = {}> = new (...args: any[]) => T;

function Timestamped<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    timestamp = new Date();
  };
}

class Example {
  exampleProperty = "example";
}

const TimestampedExample = Timestamped(Example);

const instance = new TimestampedExample();
console.log(instance.timestamp); // Outputs the current date and time

Versioning in API
API versioning allows you to manage changes to your API without breaking existing clients. Common strategies include URI versioning, query parameter versioning, and header versioning.


[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyController : ControllerBase
{
    [HttpGet]
    public IActionResult GetV1() => Ok("Version 1.0");
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class MyControllerV2 : ControllerBase
{
    [HttpGet]
    public IActionResult GetV2() => Ok("Version 2.0");
}

Clustered to Non-Primary Tables
In SQL Server, a clustered index determines the physical order of data in a table. A table can have only one clustered index, which is often created on the primary key. Non-clustered indexes are separate from the data and can be created on non-primary key columns.

SQL

-- Create a clustered index on the primary key
CREATE CLUSTERED INDEX IX_Employees_Id ON Employees(Id);

-- Create a non-clustered index on a non-primary key column
CREATE NONCLUSTERED INDEX IX_Employees_Name ON Employees(Name);

Base and Derived Class, Object of Derived Class Which Constructor Will Be Called
When an object of a derived class is created, the base class constructor is called first, followed by the derived class constructor.


public class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("Base class constructor");
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("Derived class constructor");
    }
}

// Usage
var obj = new DerivedClass();
// Output:
// Base class constructor
// Derived class constructor

Constructor in Abstract Class? Public Constructor
Abstract classes can have constructors, which are called when an instance of a derived class is created. Public constructors in abstract classes are not recommended because abstract classes cannot be instantiated directly.


public abstract class AbstractClass
{
    protected AbstractClass()
    {
        Console.WriteLine("Abstract class constructor");
    }
}

public class ConcreteClass : AbstractClass
{
    public ConcreteClass()
    {
        Console.WriteLine("Concrete class constructor");
    }
}

// Usage
var obj = new ConcreteClass();
// Output:
// Abstract class constructor
// Concrete class constructor

Comments

Popular posts from this blog

Border Radius not working in Outlook Email template

15 ways to keep your team motivated while working remotely ?