Dot NET Interview Questions


Dot NET Interview Questions

 

What is .NET Framework?

.NET Framework is a software framework developed by Microsoft that primarily runs on Microsoft Windows. It provides a large class library and supports several programming languages. It's used for building and running applications and services that use .NET technologies.

What are the main components of .NET Framework?

The main components of the .NET Framework include the Common Language Runtime (CLR), the .NET Framework Class Library, and ASP.NET for web development.

What is the Common Language Runtime (CLR)?

CLR is the heart of the .NET Framework. It provides various services such as memory management, type safety, exception handling, and garbage collection. It also compiles intermediate language code into machine code during runtime.

Explain the difference between value types and reference types in .NET.

Some key difference between value types and reference types:

Aspect Value Types Reference Types
Memory Allocation Stored on the stack or inline within data structures. Stored on the heap, and a reference to the memory location is stored on the stack or in another reference type.
Size Generally smaller in size. Generally larger in size due to overhead from heap allocation and additional metadata.
Copies When assigned to another variable or passed as a parameter, a copy of the value is created. When assigned to another variable or passed as a parameter, a copy of the reference is created, not the object itself.
Mutability Immutable by default, unless explicitly modified. Mutable, allowing modification of the underlying object's state.
Lifetime Lifetime is tied to the scope in which they are declared. Lifetime is managed by the garbage collector, and objects can persist beyond the scope in which they are created.

What is garbage collection in .NET?

Garbage collection is an automated memory management process in .NET that automatically reclaims memory occupied by objects that are no longer in use. It helps in preventing memory leaks and ensures efficient memory utilization.

What is an assembly in .NET?

An assembly is a primary unit of deployment in .NET. It contains compiled code, metadata, and resources needed to execute a program. Assemblies can be either executable (EXE) or dynamic link libraries (DLL).

Explain the difference between managed code and unmanaged code.

Some key difference between managed code and unmanaged code:

Aspect Managed Code Unmanaged Code
Execution Runs in CLR or managed environment. Runs directly on the operating system.
Memory Management Automatic memory management by the garbage collector. Manual memory management.
Type Safety Type-safe, preventing common errors. Not inherently type-safe, can lead to errors.
Interoperability Supports seamless integration within .NET. Limited interoperability with other languages.
Portability Generally more portable across platforms. May be less portable due to OS dependencies.
Performance May have overhead due to runtime environment. Offers better performance but varies.

What is the difference between an abstract class and an interface?

Some key difference between abstract class and an interface:

Aspect Abstract Class Interface
Implementation Can have method implementations. Cannot have method implementations, only signatures.
Multiple Inheritance Supports single class inheritance. Supports multiple interface inheritance.
Accessibility Can have access modifiers (public, protected, etc.). All members are public by default.
Fields Can have fields (variables) and constants. Cannot contain fields, only method and property signatures.
Constructor Can have constructors. Cannot have constructors.
Extensibility Provides flexibility with partial implementation. Provides strict contracts with full implementation.

What are delegates in C#?

Delegates are type-safe function pointers that are used to reference methods with a specific signature. They allow methods to be passed as parameters to other methods or stored as data members.

Explain the concept of inheritance in C#.

Inheritance is a fundamental object-oriented programming concept where a class (subclass or derived class) inherits properties and behavior from another class (superclass or base class). It promotes code reusability and establishes a hierarchical relationship between classes.

What is method overloading?

Method overloading is a feature in C# that allows a class to have multiple methods with the same name but with different parameter lists. It enables developers to create more readable and maintainable code by providing different ways to call a method.

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public double Add(double a, double b)
    {
        return a + b;
    }
}

What is method overriding?

Method overriding is a feature in C# that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. It enables polymorphism, where a method call on a base class reference will execute the overridden method in the derived class.

What is polymorphism?

Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. It enables flexibility and extensibility in code by allowing methods to behave differently based on the object they operate on.

What is an abstract class in C#?

An abstract class is a class that cannot be instantiated directly and may contain abstract methods, which are declared but not implemented in the abstract class. It serves as a blueprint for other classes to inherit from and provides common functionality to its derived classes.

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

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

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

What are the access modifiers available in C#?

C# provides several access modifiers such as public, private, protected, internal, and protected internal. These modifiers control the accessibility of types and type members within an assembly or across assemblies.

What is the difference between == and .Equals() method in C#?

Some key difference between == and .Equals() method:

Aspect == Operator .Equals() Method
Usage Compares the values of two objects for equality. Compares the values of two objects for equality.
Implementation Implementation can vary depending on the type. Implementation can be overridden by derived classes.
Null Handling May throw a NullReferenceException if used with null values. Typically handles null values without throwing exceptions.
Operator Overloading Can be overloaded to provide custom comparison logic. Cannot be overloaded, but .Equals() method can be overridden.

What are the different types of collections available in .NET?

Different types of collections available in .NET:

  • Arrays: Fixed-size collections of elements.
  • Lists: Dynamic collections that can grow or shrink.
  • Queues: FIFO collections for storing and retrieving elements.
  • Stacks: LIFO collections for storing and retrieving elements.
  • Dictionaries: Key-value pair collections.
  • Sets: Collections of unique elements.
  • Linked Lists: Collections where each element points to the next.
  • Sorted Lists: Automatically sorted collections of key-value pairs.
  • Hash Tables: Collections for efficient key-value pair lookup.
  • Concurrent Collections: Thread-safe collections.
  • Immutable Collections: Collections with unmodifiable contents.
  • Specialized Collections: Optimized collections for specific scenarios.

What is the difference between IEnumerable and IEnumerator in C#?

Some key difference between IEnumerable and IEnumerator:

Aspect IEnumerable IEnumerator
Purpose Represents a collection that can be enumerated. Provides the ability to iterate over a collection.
Implementation Contains a method that returns an IEnumerator. Represents an iterator over a collection.
Iteration Control Manages the iteration process externally. Controls the iteration process internally.
State Management Maintains the state of iteration throughout the enumeration process. Maintains the state of the current element being iterated.
Members Contains a single method GetEnumerator() to retrieve an IEnumerator. Contains methods like MoveNext(), Reset(), and Current property for iteration control.

What is the role of the Global Assembly Cache (GAC) in .NET?

The Global Assembly Cache (GAC) is a machine-wide repository in .NET for storing shared assemblies. It allows multiple applications to share assemblies, ensuring that only one copy of each assembly exists on the system, thereby promoting versioning and code reuse.

What is the difference between boxing and unboxing in C#?

Some key difference between boxing and unboxing:

Aspect Boxing Unboxing
Purpose Converts a value type to an object type (reference type). Converts an object type (reference type) back to a value type.
Mechanism Wraps the value type within an object reference. Extracts the value type from the object reference.
Performance Involves a performance overhead due to memory allocation and copying. Generally involves less performance overhead compared to boxing.
Implicit/Explicit Implicitly performed by the runtime when necessary. Explicitly performed by the programmer using type casting.
using System;

class Program
{
    static void Main(string[] args)
    {
        int num = 10; // Value type
        object obj = num; // Boxing

        int num2 = (int)obj; // Unboxing
    }
}

What is the difference between a struct and a class in C#?

Some key difference between a struct and a class:

Aspect Struct Class
Type Value type Reference type
Memory Allocation Typically allocated on the stack or inline within data structures. Allocated on the heap
Inheritance Does not support inheritance Supports single inheritance
Constructors Cannot have parameterless constructors or destructors. Can have parameterless constructors and destructors
Default Behavior Value types are copied by value, leading to a new copy of the struct. Reference types are copied by reference, leading to multiple references pointing to the same object.
Performance Generally more efficient for small, simple data types due to stack allocation and less memory overhead. May have more memory overhead and indirection due to heap allocation.

What is a namespace in C#?

A namespace is a logical grouping mechanism in C# that organizes code elements into a hierarchical structure to prevent naming conflicts and to improve code readability and maintainability. It helps in organizing and categorizing related classes, interfaces, structs, enums, and delegates.

What are attributes in C#?

Attributes are metadata tags that provide additional information about types, members, or other entities in C# code. They are used to convey information to the compiler or runtime about how to treat the annotated code element, such as its visibility, serialization behavior, or security requirements.

using System;

[Serializable]
public class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
}

What is the difference between the StringBuilder and String classes in C#?

Some key difference between the StringBuilder and String classess:

Aspect StringBuilder String
Mutable/Immutable Mutable: Allows modification of its contents. Immutable: Once created, cannot be changed.
Memory Usage Efficient for dynamic string manipulation due to in-place modifications. Inefficient for frequent modifications as new strings are created.
Performance Better performance for string concatenation or modification operations. May lead to performance overhead due to memory allocation for each modification.
Usage Scenarios Suitable for scenarios where string concatenation or modification is frequent. Suitable for scenarios where strings are static or rarely modified.
Methods Provides methods for appending, inserting, replacing, and removing characters. Provides methods for string manipulation and comparison.

What is an interface in C#?

An interface in C# defines a contract for classes to implement. It contains method and property declarations but does not provide any implementation. Classes that implement an interface must provide concrete implementations for all its members, thus enabling multiple classes to share common behavior.

What is the difference between a class and an interface in C#?

Some key difference between class and interface:

Aspect Class Interface
Implementation Can contain member variables, methods, constructors, etc., and provides concrete implementations. Contains method and property declarations only, without any implementations.
Inheritance Supports single class inheritance. Supports multiple interface inheritance.
Instantiation Can be instantiated to create objects. Cannot be instantiated; serves as a contract for classes to implement.
Access Modifiers Can have access modifiers like public, private, protected, etc. All members are implicitly public and cannot have access modifiers.
Multiple Inheritance Does not support multiple inheritance. Can be implemented by multiple classes.
Purpose Used for creating objects with specific behaviors and properties. Used for defining contracts that classes must adhere to, enabling polymorphism.

What is the purpose of the using statement in C#?

The using statement in C# is used to ensure that disposable objects are properly cleaned up after use. It automatically calls the Dispose method of the specified object when it goes out of scope, making it convenient for managing resources such as file streams, database connections, or network sockets.

using (var fileStream = new FileStream("example.txt", FileMode.Open))
{
    // Perform file operations
}

What is serialization in .NET?

Serialization is the process of converting an object into a stream of bytes to store it in a persistent storage medium or to transmit it over a network. .NET provides built-in support for serialization through classes like XmlSerializer, DataContractSerializer, and JsonSerializer.

using System;
using System.IO;
using System.Xml.Serialization;

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

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person { Name = "John", Age = 30 };

        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        using (TextWriter writer = new StreamWriter("person.xml"))
        {
            serializer.Serialize(writer, person);
        }
    }
}

What is deserialization in .NET?

Deserialization is the process of reconstructing an object from its serialized form, typically after it has been transmitted over a network or retrieved from a storage medium. .NET provides classes like XmlSerializer, DataContractSerializer, and JsonSerializer for deserializing objects.

What is ASP.NET?

ASP.NET is a web application framework developed by Microsoft for building dynamic web pages, web services, and web applications. It is built on top of the .NET Framework and supports various programming languages like C# and Visual Basic.NET.

using System;
using System.Web.UI;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Hello, ASP.NET!");
    }
}

What are the different types of state management techniques in ASP.NET?

ASP.NET supports various state management techniques such as view state, session state, cookies, query strings, application state, and caching. These techniques are used to preserve data across multiple requests and maintain the state of web applications.

What is ASP.NET MVC?

ASP.NET MVC (Model-View-Controller) is a web development framework for building scalable and maintainable web applications using the MVC architectural pattern. It separates the application into three main components: the model (business logic and data), the view (user interface), and the controller (request handling and response generation).

What are the advantages of using ASP.NET MVC over Web Forms?

ASP.NET MVC offers several advantages over Web Forms, including better control over HTML, cleaner separation of concerns, support for test-driven development (TDD), and improved performance due to lightweight architecture and direct interaction with HTTP.

What are the benefits of asynchronous programming in .NET?

Asynchronous programming in .NET offers several benefits, including improved responsiveness, better resource utilization, increased scalability, and enhanced user experience. It allows applications to perform long-running or I/O-bound operations efficiently without blocking the main thread.

What is ASP.NET Web API?

ASP.NET Web API is a framework for building HTTP services that can be consumed by various clients, including web browsers, mobile devices, and desktop applications. It allows developers to build RESTful APIs using HTTP verbs and content negotiation.

What is LINQ (Language Integrated Query)?

LINQ is a feature in .NET that provides a unified syntax for querying data from different data sources such as collections, arrays, XML, databases, and web services. It allows developers to write queries using a familiar syntax similar to SQL directly within C# or Visual Basic.NET code.

using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        var evenNumbers = from num in numbers
                          where num % 2 == 0
                          select num;

        foreach (var num in evenNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

What are lambda expressions in C#?

Lambda expressions are anonymous functions that enable developers to write inline, concise, and readable code for passing as arguments to methods or for defining delegates or expression trees. They provide a more functional programming style in C# and are often used with LINQ queries.

What is Entity Framework in .NET?

Entity Framework is an object-relational mapping (ORM) framework for .NET that enables developers to work with relational databases using .NET objects. It eliminates the need for writing low-level data access code by providing a higher-level abstraction over database operations.

What is asynchronous programming in .NET?

Asynchronous programming in .NET allows developers to write code that can perform non-blocking operations, enabling better responsiveness and scalability in applications. It is typically achieved using the async and await keywords in C# to execute asynchronous operations without blocking the main thread.

What is inversion of control (IoC) and dependency injection (DI) in .NET?

Inversion of control (IoC) is a design principle where the control flow of a program is inverted, such that the control of object creation and lifecycle is delegated to a container or framework. Dependency injection (DI) is a technique used to implement IoC by injecting dependencies into a class from external sources.

using System;

interface IService
{
    void Serve();
}

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

class Client
{
    private readonly IService _service;

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

    public void DoWork()
    {
        _service.Serve();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IService service = new Service();
        Client client = new Client(service);
        client.DoWork();
    }
}

What is unit testing in .NET?

Unit testing is a software testing technique where individual units or components of a software application are tested in isolation to ensure that they function correctly. In .NET, unit testing is commonly performed using frameworks like NUnit, xUnit.net, or MSTest.

using System;

class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Calculator calculator = new Calculator();
        int result = calculator.Add(5, 3);
        Console.WriteLine("Result: " + result);
    }
}

What is mocking in unit testing?

Mocking is a technique used in unit testing to create simulated objects (mock objects) that mimic the behavior of real objects. Mock objects are used to isolate the unit under test from its dependencies, allowing developers to focus on testing the unit in isolation.

What is continuous integration (CI) in .NET?

Continuous integration (CI) is a software development practice where changes to a codebase are automatically built, tested, and integrated into a shared repository on a frequent basis. In .NET, CI is often implemented using tools like Azure DevOps, Jenkins, or TeamCity.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Continuous Integration in .NET");
    }
}

What is continuous deployment (CD) in .NET?

Continuous deployment (CD) is a software development practice where code changes that pass the automated tests are automatically deployed to production environments without manual intervention. In .NET, CD is often achieved using CI/CD pipelines and release automation tools.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Continuous Deployment in .NET");
    }
}

What is the .NET Core framework?

.NET Core is a cross-platform, open-source framework for building modern, cloud-native, and high-performance applications. It is a redesigned version of the .NET Framework that is optimized for running on various operating systems, including Windows, Linux, and macOS.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(".NET Core Example");
    }
}

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

.NET Framework is a Windows-only framework that is optimized for desktop and server applications, whereas .NET Core is a cross-platform framework that is optimized for cloud-native and containerized applications. .NET Core offers better performance, modularity, and scalability compared to the .NET Framework.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(".NET Framework Example");
    }
}

What is .NET 5?

.NET 5 is the successor to both .NET Core 3.x and .NET Framework 4.x. It is a unified platform that combines the capabilities of .NET Core, .NET Framework, and Xamarin into a single framework. .NET 5 provides a consistent development experience across different platforms and workloads.

What are Blazor and Razor Pages in .NET?

Blazor and Razor Pages are two web development frameworks in .NET. Blazor is a framework for building interactive web UIs using C# instead of JavaScript. It enables developers to create rich, client-side web applications using .NET and WebAssembly. Razor Pages, on the other hand, is a lightweight web development framework for building page-focused web applications. It simplifies the development of web pages by combining the view and controller into a single Razor file, making it easier to create dynamic web content.

@page "/counter"
@using System

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

What is SignalR in .NET?

SignalR is a real-time web communication framework in .NET that enables bi-directional communication between clients and servers over a persistent connection. It allows applications to push real-time updates to connected clients asynchronously, making it ideal for building interactive web applications, chat applications, and online gaming platforms.