Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, October 22, 2024

Dotnet framework interview questions and answers

 


1. What is the .NET Framework?

  • The .NET Framework is a software development platform developed by Microsoft.
  • It provides a consistent programming model and a comprehensive set of libraries to build various applications such as web, desktop, and mobile apps.
  • It consists of two major components:
    • Common Language Runtime (CLR): Handles memory management, exception handling, and garbage collection.
    • .NET Framework Class Library (FCL): Provides reusable classes and APIs for development.

Example:

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, .NET Framework!");
    }
}

2. What is the Common Language Runtime (CLR)?

  • CLR is the heart of the .NET Framework, responsible for executing .NET programs.
  • It provides key services:
    • Memory management (using garbage collection).
    • Exception handling.
    • Thread management.
    • Security management.

Key Features of CLR:

  • Just-In-Time (JIT) Compilation: Converts Intermediate Language (IL) code to machine code.
  • Garbage Collection (GC): Automatically frees memory by removing objects that are no longer in use.

Example:

public class Example
{
    public void ShowMessage()
    {
        Console.WriteLine("CLR manages this execution.");
    }
}

3. What is the difference between .NET Framework and .NET Core?

  • .NET Framework:
    • Runs only on Windows.
    • Used for building Windows-specific applications like desktop apps.
    • Larger runtime and library support.
  • .NET Core:
    • Cross-platform (supports Windows, Linux, macOS).
    • Lightweight and modular.
    • Primarily used for web, cloud, and cross-platform apps.

4. What are Assemblies in .NET?

  • Assemblies are the building blocks of a .NET application.
  • An assembly is a compiled code that CLR can execute. It can be either an EXE (for applications) or a DLL (for reusable components).

Types of Assemblies:

  • Private Assembly: Used by a single application.
  • Shared Assembly: Can be shared across multiple applications (e.g., libraries stored in GAC).

Example:

// Compiling this code will create an assembly (DLL or EXE)
public class SampleAssembly
{
    public void DisplayMessage()
    {
        Console.WriteLine("This is an assembly example.");
    }
}

5. What is the Global Assembly Cache (GAC)?

  • GAC is a machine-wide code cache that stores assemblies specifically designated to be shared by several applications on the computer.
  • Assemblies in GAC are strongly named and allow multiple versions of the same assembly to be maintained side by side.

Example:

// To add an assembly to the GAC (in command prompt)
gacutil -i MyAssembly.dll

6. What are Namespaces in .NET?

  • Namespaces are used to organize classes and other types in .NET.
  • They prevent naming conflicts by logically grouping related classes.

Example:

namespace MyNamespace
{
    public class MyClass
    {
        public void Greet()
        {
            Console.WriteLine("Hello from MyNamespace!");
        }
    }
}

7. What is Managed Code?

  • Managed Code is the code that runs under the control of the CLR.
  • CLR manages execution, garbage collection, and other system services for the code.

Example:

// This is managed code because it's executed by CLR
public class ManagedCodeExample
{
    public void Print()
    {
        Console.WriteLine("Managed Code Example.");
    }
}

8. What is Unmanaged Code?

  • Unmanaged Code is code executed directly by the operating system, not under the control of CLR.
  • Examples include applications written in C or C++ that are compiled directly into machine code.

Example:

// Calling unmanaged code from C#
[DllImport("User32.dll")]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, int options);

9. What is the difference between Value Types and Reference Types in .NET?

  • Value Types:
    • Stored directly in memory.
    • Examples: int, float, bool.
  • Reference Types:
    • Store a reference (pointer) to the actual data in memory.
    • Examples: class, object, string.

Example:

// Value type
int x = 10;

// Reference type
string name = "John";

10. What is Boxing and Unboxing in .NET?

  • Boxing: Converting a value type to an object (reference type).
  • Unboxing: Extracting the value type from an object.

Example:

// Boxing
int num = 123;
object obj = num;  // Boxing

// Unboxing
int unboxedNum = (int)obj;  // Unboxing

 

11. What is the Common Type System (CTS)?

  • CTS defines all data types in the .NET Framework and how they are represented in memory.
  • It ensures that data types used across different .NET languages (C#, VB.NET, F#) are compatible with each other.
  • Value Types (stored in the stack) and Reference Types (stored in the heap) are both part of CTS.

Example:

// Value type
int valueType = 100;

// Reference type
string referenceType = "Hello";



12. What is the Common Language Specification (CLS)?

  • CLS defines a subset of the Common Type System (CTS) that all .NET languages must follow to ensure cross-language compatibility.
  • It provides a set of rules for data types and programming constructs that are guaranteed to work across different languages.

Example:

 // CLS-compliant code: using standard types
public class SampleClass
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

 

13. What is Just-In-Time (JIT) Compilation?

  • JIT Compilation is a process where the Intermediate Language (IL) code is converted to machine code at runtime.
  • It helps optimize execution by compiling code only when it is needed, thus saving memory and resources.

Types of JIT Compilers:

  • Pre-JIT: Compiles the entire code during deployment.
  • Econo-JIT: Compiles only required methods, reclaims memory afterward.
  • Normal JIT: Compiles methods when called for the first time.

 

 

14. What is the difference between Early Binding and Late Binding in .NET?

  • Early Binding:

    • Happens at compile time.
    • Compiler knows the method signatures and types in advance.
    • Safer and faster.
  • Late Binding:

    • Happens at runtime.
    • Uses reflection to dynamically invoke methods and access types.
    • Flexible but slower and prone to errors.

Example:

 // Early binding
SampleClass obj = new SampleClass();
obj.PrintMessage();

// Late binding using reflection
Type type = Type.GetType("SampleClass");
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("PrintMessage");
method.Invoke(instance, null);

 

15. What is Garbage Collection (GC) in .NET?

  • Garbage Collection is the process in the .NET Framework that automatically frees memory by reclaiming objects that are no longer in use.
  • GC improves memory management by cleaning up unreferenced objects.

Generations in Garbage Collection:

  1. Generation 0: Short-lived objects.
  2. Generation 1: Medium-lived objects.
  3. Generation 2: Long-lived objects.

Example:

 class Program
{
    static void Main()
    {
        // Force garbage collection
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

 

16. What is the difference between Dispose() and Finalize()?

  • Dispose():
    • Part of the IDisposable interface.
    • Must be called explicitly to release unmanaged resources.
  • Finalize():
    • Called by the Garbage Collector before an object is destroyed.
    • Cannot be called explicitly; handled by the system.

Example:

 class MyClass : IDisposable
{
    public void Dispose()
    {
        // Clean up unmanaged resources
    }
    
    ~MyClass()
    {
        // Finalizer (destructor) called by GC
    }
}

 

17. What is Reflection in .NET?

  • Reflection allows programs to inspect and interact with object metadata at runtime.
  • It can be used to dynamically create instances, invoke methods, and access fields and properties.

Example:

 Type type = typeof(SampleClass);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("PrintMessage");
method.Invoke(instance, null);

 

18. What is ADO.NET?

  • ADO.NET is a data access technology used to interact with databases (SQL, Oracle, etc.) in the .NET Framework.
  • It provides data connectivity between .NET applications and data sources, allowing you to execute SQL queries, stored procedures, and manage transactions.

Components of ADO.NET:

  • Connection: Establishes a connection to the database.
  • Command: Executes SQL statements.
  • DataReader: Reads data from a data source in a forward-only manner.
  • DataAdapter: Fills DataSet/DataTable with data.
  • DataSet/DataTable: In-memory representation of data.

Example:

 using (SqlConnection connection = new SqlConnection("connectionString"))
{
    SqlCommand command = new SqlCommand("SELECT * FROM Students", connection);
    connection.Open();
    
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        Console.WriteLine(reader["Name"]);
    }
}


19. What is the difference between DataReader and DataSet in ADO.NET?

  • DataReader:
    • Provides forward-only, read-only access to data from a database.
    • Faster and more memory-efficient.
  • DataSet:
    • In-memory representation of data that can be manipulated without being connected to the database.
    • Slower, but supports multiple tables and relationships.

 

 

20. What is ASP.NET?

  • ASP.NET is a web application framework developed by Microsoft for building dynamic web pages, websites, and web services.
  • It provides tools and libraries for building web applications with features like state management, server controls, and web forms.

Types of ASP.NET Applications:

  • Web Forms: Event-driven development model with server-side controls.
  • MVC (Model-View-Controller): A design pattern separating data, UI, and logic.
  • Web API: Used for building RESTful web services.
  • Blazor: Allows building interactive web UIs using C# instead of JavaScript.

Example (Web Forms):

 protected void Button_Click(object sender, EventArgs e)
{
    Label.Text = "Hello, ASP.NET!";
}

 

21. What are HTTP Handlers and HTTP Modules in ASP.NET?

  • HTTP Handlers:

    • Low-level components that process incoming HTTP requests directly.
    • Typically used to handle requests for specific file types (e.g., .aspx, .ashx).
  • HTTP Modules:

    • Intercepts and modifies requests/responses at various stages in the pipeline.
    • Used for authentication, logging, or custom headers.

Example (Handler):

 public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Handled by MyHandler.");
    }
    
    public bool IsReusable => false;
}

 

22. What is the difference between Session and ViewState in ASP.NET?

  • Session:
    • Stores user-specific data on the server.
    • Persists across multiple pages and requests within a session.
    • Consumes more server resources (memory).
  • ViewState:
    • Stores data in a hidden field on the client (browser) side.
    • Retains data only for a single page during postbacks.
    • Increases page size but doesn’t use server memory.

Example of ViewState:

 // Storing value in ViewState
ViewState["UserName"] = "John";

// Retrieving value from ViewState
string userName = ViewState["UserName"].ToString();

 

23. What is ASP.NET MVC?

  • ASP.NET MVC is a web development framework that follows the Model-View-Controller design pattern.
    • Model: Represents the application data and business logic.
    • View: Displays the data and the user interface.
    • Controller: Handles user input, updates the model, and selects a view to render.

Advantages:

  • Separation of concerns.
  • Easier unit testing.
  • Greater control over HTML, CSS, and JavaScript.

Example:

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

 

24. What are Action Filters in ASP.NET MVC?

  • Action Filters allow you to execute code before or after an action method is executed.
  • Common use cases include logging, authorization, and caching.

Types of Action Filters:

  • Authorization Filters (e.g., Authorize).
  • Action Filters (e.g., OnActionExecuting, OnActionExecuted).
  • Result Filters (e.g., OnResultExecuting, OnResultExecuted).
  • Exception Filters (e.g., HandleError).

Example:

 public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log before action executes
    }
}

 

25. What is Entity Framework (EF)?

  • Entity Framework is an Object-Relational Mapping (ORM) framework for .NET that allows developers to work with databases using .NET objects (classes) instead of writing SQL queries.
  • Advantages:
    • Automatic generation of database schema.
    • Enables LINQ to query the database.
    • Database migration support for schema changes.

Example:

 // Defining a model
public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
}

// Using Entity Framework to interact with the database
using (var context = new SchoolContext())
{
    var students = context.Students.ToList();
}

26. What is the difference between LINQ to SQL and Entity Framework?

  • LINQ to SQL:
    • Designed for direct database access with SQL Server.
    • Supports a one-to-one mapping between database tables and .NET classes.
    • Simpler but less feature-rich than Entity Framework.
  • Entity Framework (EF):
    • Provides more features such as inheritance, complex types, and multi-table mapping.
    • Works with multiple database providers (SQL Server, MySQL, Oracle).
    • Supports Code First, Database First, and Model First approaches.

 

 

27. What is Web API in ASP.NET?

  • ASP.NET Web API is a framework for building HTTP-based services that can be consumed by a wide variety of clients (e.g., browsers, mobile devices).
  • Web API is primarily used to create RESTful services, where HTTP verbs (GET, POST, PUT, DELETE) map to CRUD operations.

 public class ProductsController : ApiController
{
    public IEnumerable<Product> GetAllProducts()
    {
        return productList;
    }
}

 

28. What is Dependency Injection (DI) in ASP.NET?

  • Dependency Injection is a design pattern that allows injecting objects into a class, rather than creating objects inside the class.
  • It decouples the creation of objects from the business logic, making the code more modular and testable.

Example (using ASP.NET Core DI):

 public class HomeController : Controller
{
    private readonly IProductService _productService;
    
    public HomeController(IProductService productService)
    {
        _productService = productService;
    }
    
    public IActionResult Index()
    {
        var products = _productService.GetProducts();
        return View(products);
    }
}

 

29. What are REST and SOAP?

  • REST (Representational State Transfer):

    • Uses HTTP methods (GET, POST, PUT, DELETE).
    • Stateless communication.
    • JSON or XML as data format.
    • Simpler and more scalable for web APIs.
  • SOAP (Simple Object Access Protocol):

    • Uses XML for request and response messages.
    • Requires more overhead due to its strict structure and protocols.
    • Supports security features like WS-Security.

 

 

30. What is OAuth in ASP.NET?

  • OAuth is an open standard for token-based authentication, used to grant third-party applications limited access to user resources without exposing credentials.
  • OAuth is commonly used in social logins (e.g., login with Google or Facebook).


31. What is SignalR in ASP.NET?

  • SignalR is a library that allows real-time web functionality in ASP.NET applications.
  • It enables the server to send updates to clients instantly via WebSockets, long-polling, or Server-Sent Events.

Use cases:

  • Chat applications.
  • Real-time notifications.
  • Live data feeds.

Example:

 public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

 

32. What is NuGet in .NET?

  • NuGet is a package manager for .NET, allowing developers to share and consume reusable code libraries.
  • It simplifies the process of including third-party libraries into your project.

Example:

 Install-Package Newtonsoft.Json

 

33. What are Generics in C#?

  • Generics allow defining classes, interfaces, and methods with placeholders for data types.
  • They promote code reusability and type safety by allowing you to create type-agnostic data structures.

Example:

 public class GenericClass<T>
{
    public T Data { get; set; }
}

 

34. What is a delegate in C#?

  • Delegates are type-safe function pointers that allow methods to be passed as parameters.
  • Useful in implementing callback functions, events, and asynchronous programming.

Example:

 public delegate void DisplayMessage(string message);

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

DisplayMessage display = new DisplayMessage(ShowMessage);
display("Hello, World!");

 

35. What are events in C#?

  • Events provide a mechanism for a class to notify other classes or objects when something of interest occurs.
  • Events are built on top of delegates and are typically used in UI programming and handling user interactions.

Example:

 public event EventHandler ButtonClicked;

 

36. What are Extension Methods in C#?

  • Extension Methods allow you to add new methods to existing types without modifying their source code or creating a derived type.
  • Extension methods are static methods, but they are called as if they were instance methods on the extended type.

Syntax:

 public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return str.Split(' ').Length;
    }
}

// Usage
string sentence = "Hello World";
int count = sentence.WordCount();  // Output: 2

Key Points:

  • Defined in static classes.
  • The first parameter specifies the type being extended, and the keyword this is used before the type.

 

37. What is the difference between finalize and dispose methods?

  • Finalize:

    • Called by the garbage collector before an object is destroyed.
    • Used to release unmanaged resources.
    • Cannot be called explicitly in code.
    • Defined using a destructor in C#.
  • Dispose:

    • Explicitly called by the developer to release unmanaged resources.
    • Part of the IDisposable interface.
    • Should be used when working with resources like file handles or database connections.

Example using Dispose:

 public class ResourceHolder : IDisposable
{
    private bool disposed = false;
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Free managed resources
            }
            // Free unmanaged resources
            disposed = true;
        }
    }
    
    ~ResourceHolder()
    {
        Dispose(false);
    }
}

 

38. What is the using statement in C#?

  • The using statement is used to automatically manage the disposal of unmanaged resources.
  • It ensures that Dispose() is called on objects that implement IDisposable, even if an exception occurs.

Example:

 using (var reader = new StreamReader("file.txt"))
{
    string content = reader.ReadToEnd();
}
// `Dispose()` is automatically called on `StreamReader`.

 

39. What is a sealed class in C#?

  • A sealed class cannot be inherited by other classes. It restricts the class hierarchy by preventing inheritance.
  • Sealing a class can be useful for security, performance, or if you want to ensure the class’s implementation stays unchanged.

Example:

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

 

40. What is the lock statement in C#?

  • The lock statement is used to ensure that a block of code is executed by only one thread at a time. It provides thread-safety by preventing race conditions.
  • Typically used when working with shared resources in multi-threaded applications.

Example:

 private static object _lock = new object();

public void CriticalSection()
{
    lock (_lock)
    {
        // Code that must be synchronized
    }
}

 

41. What are Indexers in C#?

  • Indexers allow objects to be indexed like arrays. They enable a class to be accessed using square brackets [], similar to array elements.

Example:

 public class SampleCollection
{
    private string[] elements = new string[100];
    
    public string this[int index]
    {
        get { return elements[index]; }
        set { elements[index] = value; }
    }
}

// Usage
SampleCollection collection = new SampleCollection();
collection[0] = "First Element";
Console.WriteLine(collection[0]); // Output: First Element

 

42. What is the difference between Array and ArrayList in C#?

  • Array:

    • Fixed size, strongly-typed (can only hold one data type).
    • Faster performance due to strong typing.
  • ArrayList:

    • Dynamic size, but not strongly-typed (can hold different data types).
    • Uses more memory and is slower compared to arrays due to boxing and unboxing of value types.

Example:

 // Array
int[] numbers = new int[5];

// ArrayList
ArrayList list = new ArrayList();
list.Add(1);
list.Add("String"); // Mixed types

 

43. What is a Multicast Delegate in C#?

  • A Multicast Delegate can hold references to multiple methods. When invoked, it calls all the methods in its invocation list.

Example:

 public delegate void Notify();

public class DelegateExample
{
    public static void Method1() { Console.WriteLine("Method1"); }
    public static void Method2() { Console.WriteLine("Method2"); }

    public static void Main()
    {
        Notify notifyDelegate = Method1;
        notifyDelegate += Method2; // Multicast
        notifyDelegate.Invoke();
    }
}

// Output:
// Method1
// Method2

 

44. What is the difference between IEnumerable and IQueryable in C#?

  • IEnumerable:

    • Suitable for in-memory data collection.
    • Queries are executed in memory.
    • Supports LINQ to Objects and LINQ to XML.
  • IQueryable:

    • Suitable for out-of-memory data (e.g., databases).
    • Queries are executed on the data source (e.g., SQL database).
    • Supports deferred execution and LINQ to SQL.

Example:

 // Using IQueryable for deferred execution
IQueryable<Product> query = dbContext.Products.Where(p => p.Price > 50);

// Using IEnumerable
IEnumerable<Product> products = query.ToList();

 

45. What are anonymous methods in C#?

  • Anonymous methods allow you to define inline, unnamed methods using the delegate keyword.
  • They are used for shorter, simpler delegate expressions, and can capture variables from their surrounding scope.

Example:

 Func<int, int> square = delegate (int x)
{
    return x * x;
};

int result = square(5);  // Output: 25

 

46. What are Lambda Expressions in C#?

  • Lambda expressions are concise ways to write anonymous methods. They are used extensively in LINQ queries.

Example:

 Func<int, int> square = x => x * x;

int result = square(5);  // Output: 25

 

47. What is the role of yield in C#?

  • yield allows methods to return elements of a collection one at a time, without storing them all in memory. It's useful for creating custom iterator methods.

Example:

 public IEnumerable<int> GetNumbers()
{
    for (int i = 1; i <= 5; i++)
    {
        yield return i;
    }
}

// Usage
foreach (int number in GetNumbers())
{
    Console.WriteLine(number);
}

 

48. What is Reflection in C#?

  • Reflection allows inspecting and interacting with the metadata of types, methods, and properties at runtime.

Use cases:

  • Creating objects dynamically.
  • Invoking methods at runtime.
  • Accessing private fields and methods.

Example:

 Type type = typeof(MyClass);
MethodInfo method = type.GetMethod("MyMethod");
method.Invoke(Activator.CreateInstance(type), null);

 

49. What is the purpose of is and as operators in C#?

  • is: Checks if an object is of a specific type.
  • as: Attempts to cast an object to a specific type, returning null if the cast fails.

Example:

 object obj = "Hello";

if (obj is string)
{
    string str = obj as string;
    Console.WriteLine(str);
}

 

50. What is the out keyword in C#?

  • The out keyword allows a method to return multiple values by passing arguments by reference.
  • Parameters marked with out must be assigned a value before the method returns.

Example:

 public void GetValues(out int a, out int b)
{
    a = 10;
    b = 20;
}

// Usage
int x, y;
GetValues(out x, out y);
Console.WriteLine($"x = {x}, y = {y}");

 

51. What is a Strong Name in .NET?

  • A Strong Name uniquely identifies an assembly using its name, version, culture, and public key token.
  • Strongly named assemblies are stored in the GAC and help in avoiding conflicts between versions.

Example:

 sn -k MyKey.snk

 

52. What is the difference between const and readonly in C#?

  • const:
    • Compile-time constant.
    • Value cannot change.
    • Must be assigned at declaration.
  • readonly:
    • Runtime constant.
    • Can be assigned at runtime in the constructor.

Example:

 const int maxItems = 100;
readonly int maxLimit;

 

53. What is the purpose of sealed methods in C#?

  • A sealed method is a method that prevents overriding in derived classes.
  • Only applies to methods in base classes marked virtual or override.

Example:

 public override sealed void Method()
{
    // This method cannot be overridden further.
}

 

54. What is the difference between throw and throw ex in exception handling?

  • throw: Re-throws the original exception while preserving the stack trace.
  • throw ex: Resets the stack trace, making it harder to trace the original error.

Example:

 try
{
    // Some code
}
catch(Exception ex)
{
    throw; // Preserves original exception
}

 

55. What is the difference between Task and Thread in C#?

  • Task: Higher-level abstraction for managing asynchronous operations. It supports continuations and better integrates with async/await.
  • Thread: Lower-level, represents a unit of execution in the system.

 

 

56. What is Lazy<T> in C#?

  • Lazy<T> provides a way to delay the initialization of an object until it is needed (lazy loading).

Example:

 Lazy<MyClass> lazyObj = new Lazy<MyClass>(() => new MyClass());

 

57. What is the difference between Abstract Class and Interface in C#?

  • Abstract Class:
    • Can have method implementations.
    • Supports access modifiers.
    • Can contain constructors.
  • Interface:
    • Only method declarations (before C# 8.0).
    • Cannot have access modifiers.
    • No constructors.

 

58. What is the difference between synchronous and asynchronous programming?

  • Synchronous:
    • Blocking, one operation must complete before another can start.
  • Asynchronous:
    • Non-blocking, allows operations to run in parallel or independently.

Example:

 await Task.Delay(1000); // Asynchronous call

 

59. What is the Func delegate in C#?

  • Func is a built-in delegate type that returns a value. It can take up to 16 input parameters.

Example:

 Func<int, int, int> add = (x, y) => x + y;

 

60. What is the difference between String and StringBuilder?

  • String: Immutable, every change creates a new string object.
  • StringBuilder: Mutable, optimized for multiple manipulations on strings.

 

 

61. What is the Singleton Design Pattern?

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

Example:

 public class Singleton
{
    private static Singleton _instance;
    private Singleton() { }

    public static Singleton Instance => _instance ??= new Singleton();
}

 

62. What is Memory Leak in .NET and how to prevent it?

  • A Memory Leak occurs when objects are no longer used but not freed, causing memory exhaustion.
  • To prevent it:
    • Dispose unmanaged resources properly.
    • Use weak references where applicable.
    • Implement the IDisposable interface.

 

63. What is the difference between Task.Run() and TaskFactory.StartNew()?

  • Task.Run(): Suitable for CPU-bound operations and preferred for new code.
  • TaskFactory.StartNew(): Offers more configuration options and is more flexible.

 

64. What is the volatile keyword in C#?

  • The volatile keyword ensures that a variable's value is always read from memory, preventing optimizations that might cache its value in CPU registers.

 

65. What is the difference between Task.Wait() and Task.Result?

  • Task.Wait(): Blocks the calling thread until the task completes.
  • Task.Result: Blocks the thread and retrieves the task’s result.

 

66. What is the difference between a Shallow Copy and a Deep Copy?

  • Shallow Copy: Copies the reference types as references (pointers).
  • Deep Copy: Copies the actual objects, creating new instances.

 

67. What is the difference between a List<T> and an Array in C#?

  • List<T>: Dynamic size, resizable, part of System.Collections.Generic.
  • Array: Fixed size, cannot resize after creation.

 

68. What are Nullable Types in C#?

  • Nullable types allow value types to have null values, using the ? syntax.

Example:

 int? num = null;

 

69. What is the difference between First() and FirstOrDefault() in LINQ?

  • First(): Throws an exception if no element is found.
  • FirstOrDefault(): Returns a default value (like null or 0) if no element is found.

 

70. What is yield in C#?

  • yield is used to create an iterator block, returning each element of a collection one at a time without creating the entire collection in memory.

 

71. What are the differences between Task and ThreadPool?

  • Task: Used for managing parallel code.
  • ThreadPool: Manages a pool of worker threads to perform tasks.

 

72. What is the lock keyword in C#?

  • lock is used to ensure that a block of code runs exclusively in a multi-threaded environment, preventing race conditions.

 

73. What is IEnumerable<T> in C#?

  • IEnumerable<T> represents a forward-only, read-only collection of a sequence of elements.

 

 

74. What is Covariance and Contravariance in C#?

  • Covariance allows a method to return a more derived type than the specified type.
  • Contravariance allows a method to accept arguments of a more general type than the specified type.

 

75. What is a Mutex in .NET?

  • A Mutex is used for synchronizing access to a resource across multiple threads and processes.

 

76. What are Tuples in C#?

  • A Tuple is a data structure that can hold multiple values of different types.

Example:

 var tuple = Tuple.Create(1, "Hello", true);

 

77. What is the difference between ToString() and Convert.ToString()?

  • ToString(): Can throw an exception if the object is null.
  • Convert.ToString(): Returns an empty string if the object is null.

 

78. What is the ThreadLocal<T> class in C#?

  • ThreadLocal<T> provides thread-local storage, meaning each thread has its own separate instance of a variable.

 

79. What is the ICloneable interface in C#?

  • The ICloneable interface provides a mechanism for creating a copy of an object.

 

80. What is the WeakReference class in C#?

  • A WeakReference allows an object to be garbage collected while still allowing a reference to the object.

 

 

 


Saturday, April 15, 2023

How do you use Identity Framework for authentication in ASP.NET Core?

ASP.NET Core Identity is a membership system that allows you to authenticate and authorize users. It provides a set of APIs and UI components for managing users, roles, and permissions in your application.

Here's an overview of how to use Identity Framework for authentication in ASP.NET Core:

1. Install the Identity Framework package: In your project, add the following package reference to the .csproj file:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="x.x.x" />
</ItemGroup> 

2. Configure the Identity Framework: In the Startup.cs file, add the following code to configure the Identity Framework:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<ApplicationUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    // ...
}

This code sets up the Identity Framework with the default UI and authentication settings. It also configures the Identity Framework to use the ApplicationDbContext as the data store.


3. Create a user: You can create a new user using the UserManager<TUser>.CreateAsync method:


var user = new ApplicationUser { UserName = "johndoe@example.com", Email = "johndoe@example.com" };
var result = await _userManager.CreateAsync(user, "password123");

This code creates a new user with the email and username of "johndoe@example.com" and a password of "password123".


4. Authenticate the user: In your login action, use the SignInManager<TUser>.PasswordSignInAsync method to authenticate the user:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
    return RedirectToAction("Index", "Home");
}


This code authenticates the user by email and password. If the authentication is successful, it redirects the user to the home page.

5. Protect resources: Use the [Authorize] attribute on actions or controllers to protect resources that require authentication:
[Authorize]
public class HomeController : Controller
{
    // ...
}


This code ensures that only authenticated users can access the actions or controllers that are marked with the [Authorize] attribute.

6. Log out the user: In your logout action, use the SignInManager<TUser>.SignOutAsync method to sign out the user:

await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");


This code signs out the user and redirects them to the home page.

Using Identity Framework for authentication in ASP.NET Core can provide a powerful and customizable solution for managing user authentication and authorization in your application.

 

 

What is a JWT token and how is it used in authentication?

JWT stands for JSON Web Token, and it is a compact, URL-safe means of representing claims to be transferred between two parties. JWT is often used for authentication and authorization purposes in web applications.

JWT tokens consist of three parts: a header, a payload, and a signature. The header contains information about the type of token and the algorithm used for signing the token. The payload contains the claims or information that the token represents, such as the user's ID, username, or roles. The signature is used to verify the authenticity of the token and ensure that it has not been tampered with.

JWT tokens are commonly used in authentication to provide a stateless mechanism for verifying the identity of a user. Here's how it works:

  1. The user logs in to the application with their credentials, such as a username and password.
  2. The server verifies the user's credentials and generates a JWT token.
  3. The JWT token is returned to the client and stored in the browser's local storage or a cookie.
  4. For subsequent requests to the server, the client sends the JWT token in the request header.
  5. The server verifies the JWT token and grants access to the requested resource if the token is valid.

Using JWT tokens for authentication has several benefits, including improved performance, scalability, and security. Since the JWT token contains all the necessary information to authenticate a user, there is no need to store user sessions on the server, which improves performance and scalability. Also, since the token is signed, it cannot be tampered with or forged, which improves security.

What is the difference between authentication and authorization?

Authentication and authorization are two distinct concepts in the context of security in software systems.

Authentication is the process of verifying the identity of a user or system. In other words, it is a mechanism that confirms the validity of a user's claimed identity, such as a username and password, or a digital certificate. The main goal of authentication is to ensure that a user is who they claim to be before granting access to a resource or service.

Authorization, on the other hand, is the process of determining whether a user or system has the necessary permissions to access a particular resource or perform a specific action. Authorization involves checking whether a user or system has the required rights, roles, or privileges to perform an operation or access a resource. The goal of authorization is to ensure that only authorized users have access to the appropriate resources and actions.

In summary, authentication is about verifying the identity of a user or system, while authorization is about determining whether that user or system has the necessary permissions to perform a specific action or access a resource. These two concepts are closely related and often used together to provide secure access to software systems.

How do you implement authentication and authorization in ASP.NET Core?

In ASP.NET Core, authentication and authorization can be implemented using middleware components and ASP.NET Core Identity.

Authentication 

Authentication is the process of verifying the identity of a user. Here are the steps to implement authentication in an ASP.NET Core application:

  1. Configure the authentication middleware component in the Startup.cs file. This can be done using the services.AddAuthentication() method and specifying the authentication scheme, such as cookies, tokens, or external providers.
  2. Add authentication attributes to the controllers or actions that require authentication. This can be done using the [Authorize] attribute.
  3. Implement the login and logout functionality in the application. This can be done using the SignInManager and UserManager classes provided by ASP.NET Core Identity.



Authorization 

Authorization is the process of determining whether a user has access to a specific resource or action. Here are the steps to implement authorization in an ASP.NET Core application:

  1. Configure the authorization middleware component in the Startup.cs file. This can be done using the services.AddAuthorization() method and specifying the policy requirements.
  2. Define the authorization policies in the application. This can be done using the AuthorizationPolicyBuilder class and specifying the requirements for each policy.
  3. Add authorization attributes to the controllers or actions that require authorization. This can be done using the [Authorize] attribute with the policy name.
  4. Implement the custom authorization requirements if necessary. This can be done by creating a class that implements the IAuthorizationRequirement interface and registering it in the application's service collection.


Overall, implementing authentication and authorization in ASP.NET Core requires a combination of middleware components, ASP.NET Core Identity, and custom code. By following the above steps, you can secure your ASP.NET Core application and ensure that users only have access to the appropriate resources and actions.

How do you use the Model-View-Controller (MVC) pattern in ASP.NET Core?

In ASP.NET Core, the Model-View-Controller (MVC) pattern is used to structure web applications. The MVC pattern separates the application into three main components:

  • Model: The model represents the data and business logic of the application. It typically includes classes that represent the data entities and methods to manipulate the data.
  • View: The view represents the user interface of the application. It typically includes HTML templates that display the data to the user.
  • Controller: The controller handles user input and coordinates the interaction between the model and the view. It typically includes methods that respond to user requests and perform the necessary processing.


Here's an example of how to use the MVC pattern in an ASP.NET Core application:

  1. Create a new ASP.NET Core web application using the MVC template.
  2. Define the model classes in the application. These can be simple classes that represent data entities or more complex classes that include methods for manipulating the data.
  3. Define the view templates in the application. These can be HTML files that include Razor syntax for displaying data from the model.
  4. Define the controller classes in the application. These classes will handle user input and coordinate the interaction between the model and the view. Each action method in the controller will typically perform the following steps:
    • Receive input from the user (either in the form of query parameters, form data, or JSON data).
    • Use the model classes to perform any necessary data manipulation or processing.
    • Return a view template that displays the data to the user.
  5. Configure the application routing to map incoming requests to the appropriate controller and action method.
  6. Run the application and test the MVC pattern by submitting requests and verifying that the appropriate views are returned with the expected data.
Overall, the MVC pattern is a powerful way to structure web applications and promote separation of concerns between the different components of the application. By separating the data, logic, and presentation into separate components, it makes the application easier to develop, test, and maintain.

 

What is a tag helper in ASP.NET Core and how does it work?

A tag helper is a feature of ASP.NET Core that allows you to create custom HTML tags and attributes that can be used in Razor views. Tag helpers are a way to encapsulate complex HTML markup and logic into reusable components that can be easily integrated into your application.

Tag helpers are defined as C# classes that derive from the TagHelper base class and are decorated with the HtmlTargetElement attribute to specify the HTML elements that the tag helper applies to. Tag helpers can then implement the ProcessAsync method to modify the HTML markup and attributes of the element.

Here's an example of a simple tag helper that adds a custom attribute to a div element:

[HtmlTargetElement("div", Attributes = "custom-attribute")]
public class CustomTagHelper : TagHelper
{
    public string CustomAttribute { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.Attributes.SetAttribute("data-custom-attribute", CustomAttribute);
        await base.ProcessAsync(context, output);
    }
}


In this example, the CustomTagHelper class is defined to target div elements with a custom-attribute attribute. The CustomAttribute property is used to set the value of the data-custom-attribute attribute in the generated HTML markup. The ProcessAsync method is used to modify the TagHelperOutput object that represents the generated HTML markup.

To use the tag helper in a Razor view, you can use the tag helper syntax:

 <div custom-attribute="Hello, world!" />

In this example, the div element is decorated with the custom-attribute attribute, which is processed by the CustomTagHelper class to generate the HTML markup with the data-custom-attribute attribute set to the value "Hello, world!".

Tag helpers can also be used to generate complex HTML markup, handle user input, and perform server-side processing. Tag helpers are a powerful way to encapsulate HTML markup and logic into reusable components that can be easily integrated into your application.

 

 

What is a Razor view and how do you use it in ASP.NET Core?

A Razor view is a template-based view engine in ASP.NET Core that uses the Razor syntax to generate HTML markup. Razor views are used to define the user interface of an application and can be used to display dynamic content based on data provided by the controller.

To use a Razor view in an ASP.NET Core application, you first need to create a view file with the .cshtml file extension. Views are typically stored in the Views folder in your application and organized into subfolders based on the corresponding controller. For example, a view for the Index action of the HomeController would typically be located at Views/Home/Index.cshtml.

Here's an example of a simple Razor view:

@model MyNamespace.Models.MyModel

<h1>Welcome to my application!</h1>

<p>Hello, @Model.Name!</p>

<ul>
@foreach (var item in Model.Items)
{
    <li>@item</li>
}
</ul>
 

 

In this example, the @model directive is used to specify the model type for the view. The model type is typically a class that defines the data that will be displayed in the view. The @Model keyword is then used to access properties of the model within the view.

The Razor syntax is used to generate HTML markup and control the flow of the view. For example, the @foreach statement is used to loop over items in a collection and generate HTML markup for each item.

To render a Razor view in an action method of a controller, you can use the View method:

 public IActionResult Index()
{
    var model = new MyModel
    {
        Name = "John",
        Items = new List<string> { "Item 1", "Item 2", "Item 3" }
    };

    return View(model);
}


In this example, the View method is used to return a view with a model of type MyModel. The view engine will automatically locate the view file based on the naming convention and folder structure, and generate HTML markup based on the Razor syntax and model data.

You can also use layouts and partial views to define reusable portions of the user interface, and render them within your Razor views using the @layout and @partial directives, respectively.

How do you configure routing in ASP.NET Core?

Routing in ASP.NET Core is responsible for mapping incoming HTTP requests to the appropriate action methods in a controller. By default, ASP.NET Core uses a set of conventions to determine which action method to execute based on the request URL and HTTP verb. However, you can customize the routing behavior by configuring the routing middleware in the Configure method of your Startup class.

Here's an example of how to configure routing in ASP.NET Core:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}



In this example, the UseRouting method is called to enable routing middleware. The UseEndpoints method is then called to define the endpoints for the application. The MapControllerRoute method is used to map incoming requests to action methods in a controller.

The MapControllerRoute method takes three arguments:name: A unique name for the route.
  • pattern: The URL pattern that the route will match. This pattern can include placeholders for route parameters, which are enclosed in curly braces ({}).
  • defaults: An object that specifies default values for route parameters.

In this example, the default route is defined with a URL pattern of "{controller=Home}/{action=Index}/{id?}". This means that if no controller or action is specified in the URL, the HomeController and Index action method will be used by default. The id parameter is optional and can be omitted from the URL.

You can define multiple routes by calling the MapControllerRoute method multiple times with different patterns and names. The ASP.NET Core routing system will try to match incoming requests to the defined routes in the order that they are defined, using the first route that matches.

You can also define routes using attributes on the controller and action methods. This is known as attribute routing and provides a more explicit way to define the URL patterns for your application. To enable attribute routing, call the AddControllers method with the [ApiController] attribute in the ConfigureServices method:

 public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddControllers().AddNewtonsoftJson();

    // ...
}



Then, decorate your controller and action methods with the [Route] attribute:

[Route("api/[controller]")]
public class MyController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        // ...
    }

    [HttpPost]
    public IActionResult Post([FromBody] MyModel model)
    {
        // ...
    }
}
 

In this example, the MyController class is decorated with the [Route] attribute with a template of "api/[controller]", which means that all URLs for this controller will begin with "api/" followed by the controller name. The HttpGet and HttpPost attributes are used to define the HTTP verb and URL pattern for each action method. The {id} placeholder in the HttpGet attribute represents a route parameter that will be passed to the Get method as an argument. 

 

What is an action filter in ASP.NET Core and how does it work?

An action filter is a type of middleware in ASP.NET Core that is used to execute code before or after an action method is executed. Action filters can be used to modify the request or response, perform authentication or authorization checks, add or remove headers or cookies, or log information about the request or response.

Action filters are applied to action methods in a controller using attributes. For example, the [Authorize] attribute is an action filter that is used to ensure that the user is authenticated before executing the action method. Other common action filters in ASP.NET Core include [AllowAnonymous], [ValidateAntiForgeryToken], [RequireHttps], and [ResponseCache].

Here's an example of how to create a custom action filter in ASP.NET Core:
 

public class LogActionFilter : IActionFilter

{

private readonly ILogger _logger;


public LogActionFilter(ILogger<LogActionFilter> logger)

{

     _logger = logger;

}


public void OnActionExecuting(ActionExecutingContext context)

{

     _logger.LogInformation("Action method {ActionName} is executing.", context.ActionDescriptor.DisplayName);

}


public void OnActionExecuted(ActionExecutedContext context)

{

     _logger.LogInformation("Action method {ActionName} has completed with status code {StatusCode}.",

                             context.ActionDescriptor.DisplayName, context.HttpContext.Response.StatusCode);

}

}

 

In this example, the LogActionFilter class implements the IActionFilter interface, which defines two methods: OnActionExecuting and OnActionExecuted. These methods are called by the ASP.NET Core framework before and after the action method is executed, respectively.

In the OnActionExecuting method, the action filter logs a message indicating that the action method is executing, along with its display name. In the OnActionExecuted method, the action filter logs a message indicating that the action method has completed, along with its display name and the HTTP status code of the response.

To apply this action filter to an action method in a controller, you can add the [ServiceFilter] attribute to the method and specify the type of the action filter: 
 
 

[ServiceFilter(typeof(LogActionFilter))]

public IActionResult Index()

{

return View();

}

 


This will cause the LogActionFilter to be executed before and after the Index action method is executed.

 

What is middleware in ASP.NET Core and how does it work?

Middleware in ASP.NET Core is software components that are placed in the request processing pipeline to handle requests and responses in a modular and composable way. Each middleware component in the pipeline performs a specific task, such as authentication, routing, logging, or caching, and can be added or removed as needed to create custom request processing pipelines.

The middleware pipeline in ASP.NET Core is composed of one or more middleware components that are executed sequentially in the order they are added. Each middleware component can perform some operation on the incoming request or outgoing response, such as modifying headers, redirecting requests, or returning a response directly.

Here's an example of how middleware works in ASP.NET Core:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

if (env.IsDevelopment())

{

     app.UseDeveloperExceptionPage();

}

else

{

     app.UseExceptionHandler("/Error");

     app.UseHsts();

}


app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>

{

     endpoints.MapControllers();

});

}

In this example, the Configure method in the Startup class sets up the middleware pipeline for an

ASP.NET Core application. The first middleware component is the DeveloperExceptionPage middleware, which displays detailed error information in the response when running in development mode. This middleware is only added to the pipeline if the application is running in development mode.

The next middleware component is the ExceptionHandler middleware, which handles exceptions that occur during request processing and returns an error response. This middleware is added to the pipeline for all environments.

The HttpsRedirection middleware and StaticFiles middleware handle HTTP redirection and static file serving, respectively. These middleware components are added to the pipeline for all requests.

The Routing middleware and Authorization middleware handle routing and authentication/authorization, respectively. These middleware components are added to the pipeline for all requests.

Finally, the Endpoints middleware maps the incoming requests to the appropriate controller action method based on the route template. This middleware is added to the pipeline for all requests.

By composing middleware components in this way, you can build custom request processing pipelines that handle requests and responses in a flexible and modular way.

 

 

What is the difference between transient, scoped, and singleton services in .NET Core?

DI Service Lifetimes

 
In .NET Core, services registered with the dependency injection container can be registered as either transient, scoped, or singleton. These lifetimes control how many instances of a service are created and how long they are held in memory.

Transient services are created each time they are requested. Every time you request an instance of a transient service, a new instance is created. Transient services are good for lightweight, stateless services that can be easily created and destroyed. For example, a Random number generator might be a good candidate for a transient service.


Scoped services are created once per request (i.e., per HTTP request in the case of an ASP.NET Core application). Once a scoped service has been created, it is used for the duration of the request, and then destroyed. Scoped services are useful for stateful services that need to be reused across multiple objects or components during the processing of a single request. For example, a database context might be a good candidate for a scoped service.


Singleton services are created once and reused for the lifetime of the application. A single instance of the service is created when the application starts up and then reused across all requests. Singleton services are good for services that are expensive to create or that hold application-level state. For example, a configuration service that reads configuration settings from a file might be a good candidate for a singleton service.


It's important to choose the appropriate lifetime for your services based on their usage and resource requirements. Choosing the wrong lifetime can lead to performance problems, memory leaks, or unexpected behavior.