.NET interview questions can cover a wide range of topics, and it is important for a candidate to have a solid understanding of the .NET platform and its capabilities in order to be successful in a .NET interview. .NET is a popular platform for building applications on the Windows operating system. As such, there are many interview questions that are commonly asked in .NET interviews. These questions can range from general questions about the .NET platform and its capabilities, to more specific questions about the programming languages and technologies that are used with .NET. Here are few questions with answers on .NET framework:
C#:
What is a class, object, interface, abstract class in C#?
In C#, a class is a blueprint for creating objects. It defines the properties and behaviors that the objects of the class will have. An object is an instance of a class. It represents a specific entity with its own state and behaviors. An interface is a set of related methods that a class or struct can implement. It is a way to specify a contract for the behaviors that a class must implement. An abstract class is a class that cannot be instantiated and serves as a base for one or more derived classes. It can contain abstract methods, which are methods without a body, that must be implemented by the derived classes. Abtract classes are used to provide a common interface or implementation for derived classes.
What is the difference between a struct and a class in C#?
There are several differences between structs and classes in C#:
- Structs are value types, while classes are reference types. This means that when you assign a struct to a variable, the value of the struct is copied to the variable. On the other hand, when you assign a class to a variable, the variable stores a reference to an object, rather than the object itself.
- Structs cannot have a default constructor. This means that you must initialize all of the fields in a struct when you create an instance of it. Classes, on the other hand, can have a default constructor, which is a constructor with no parameters.
- Structs cannot be inherited from other classes or structs. They are standalone types. Classes, on the other hand, can be derived from other classes or interfaces.
- Structs are usually used for simple data types that have a small number of fields and do not require inheritance or complex behavior. Classes are generally used for more complex data types that require inheritance, encapsulation, and polymorphism.
In general, you should use structs when you need to store small amounts of data and performance is important, and use classes when you need more complex behavior.
What is a delegate in C#?
In C#, a delegate is a type that represents a reference to a method. It is similar to a function pointer in C or C++, but is safer and more flexible.
Delegates are used to pass methods as arguments to other methods. They are often used to implement event handling and callbacks in C#.
To declare a delegate, you can use the delegate
keyword followed by the return type and the parameter list of the methods that the delegate can reference. For example:
delegate int MyDelegate(int x, int y);
This declares a delegate named MyDelegate
that can reference methods with two integer parameters and a return type of int
.
To create an instance of a delegate, you can use the new
operator and pass a method as an argument. For example:
MyDelegate del = new MyDelegate(Method1);
This creates a delegate that references the Method1
method. You can then call the method using the delegate:
int result = del(10, 20); // Calls the Method1 method
You can also use anonymous methods or lambda expressions to create delegates. For example:
MyDelegate del = delegate(int x, int y) { return x + y; }; // Anonymous method
MyDelegate del = (x, y) => x + y; // Lambda expression
Delegates are useful for implementing loosely coupled code, where one part of the code does not need to know the details of how another part of the code is implemented. They provide a way to pass a method as an argument, which allows the calling code to execute the method at a later time or under certain conditions.
What is an event in C#?
In C#, an event is a way to notify other parts of the code when something interesting happens. It is a way to publish and subscribe to notifications.
An event is declared using the event
keyword, followed by a delegate type and the event name. For example:
public event EventHandler MyEvent;
This declares an event named MyEvent
that can be used to notify other parts of the code when something happens. The EventHandler
delegate is a predefined delegate type that represents a method that takes an object and an EventArgs
object as parameters and returns void.
To raise an event, you can use the raise
keyword followed by the event name and any required arguments. For example:
if (MyEvent != null)
{
MyEvent(this, EventArgs.Empty);
}
This raises the MyEvent
event, passing the current object and an empty EventArgs
object as arguments.
To subscribe to an event, you can use the +=
operator and pass a method as an argument. For example:
MyClass obj = new MyClass();
obj.MyEvent += Method1;
This subscribes the Method1
method to the MyEvent
event. When the event is raised, the Method1
method will be called.
You can also use anonymous methods or lambda expressions to subscribe to events. For example:
MyClass obj = new MyClass();
obj.MyEvent += delegate(object sender, EventArgs e) { /* Event handling code goes here */ }; // Anonymous method
MyClass obj = new MyClass();
obj.MyEvent += (sender, e) => { /* Event handling code goes here */ }; // Lambda expression
Events are useful for decoupling different parts of the code and allowing them to communicate with each other in a loosely coupled way. They provide a way for one part of the code to publish notifications, and for another part of the code to receive and handle those notifications.
What is a generics in C#?
Generics is a feature in C# that allows you to define classes, interfaces, and methods that can work with any data type. It is a way to create reusable, type-safe code that can be used with different data types without the need to write separate versions for each data type.
To create a generic class, you can use the <T>
syntax, where T
is a placeholder for the data type. For example:
class MyList<T>
{
// Properties and methods of the class
}
This creates a generic class named MyList
that can be used with any data type.
To create a generic method, you can use the same <T>
syntax in the method declaration. For example:
class MyClass
{
public static T Max<T>(T x, T y)
{
// Implementation of the method
}
}
This creates a generic method named Max
that can be used to find the maximum value between two values of any data type.
You can specify constraints on the data type by using the where
keyword. For example:
class MyClass
{
public static T Max<T>(T x, T y) where T : IComparable<T>
{
// Implementation of the method
}
}
This creates a generic method that can be used only with data types that implement the IComparable<T>
interface. This ensures that the values can be compared using the CompareTo
method.
Generics are useful for creating reusable and type-safe code that can be used with different data types. They allow you to write code that is flexible and adaptable to different data types, while still ensuring that the code is correct and safe.
What is an async/await in C#?
The async
and await
keywords in C# are used to implement asynchronous programming. Asynchronous programming allows you to perform long-running operations in the background, without blocking the main thread or the user interface.
The async
keyword is used to mark a method as asynchronous. An async method contains one or more await
expressions, which specify points where the method can be paused while it waits for a task to complete.
Here is an example of an async method:
async Task<int> GetResultAsync()
{
var result = await DoSomethingAsync(); // The method is paused here while DoSomethingAsync completes
return result;
}
The await
operator is used to wait for a task to complete and get its result. It can be used only in an async method and only when the task has a result.
The async
and await
keywords allow you to write asynchronous code that looks and behaves like synchronous code. They make it easier to write asynchronous code that is easy to read, understand, and maintain.
Asynchronous programming is useful for improving the performance and responsiveness of applications, especially when dealing with I/O-bound or CPU-bound operations. It allows you to perform long-running operations in the background, without blocking the main thread or the user interface.
.NET:
What is the Common Language Runtime (CLR)?
The Common Language Runtime (CLR) is the execution engine of the .NET Framework. It is responsible for executing managed code and providing services to the code, such as memory management, security, and exception handling.
The CLR is a runtime environment that is designed to be language-agnostic. This means that it can execute code written in any .NET-supported programming language, such as C#, VB.NET, and F#.
The CLR is responsible for several tasks, for example:
- Compiling and executing managed code: The CLR compiles managed code into an intermediate language (IL) and then executes the IL using a Just-In-Time (JIT) compiler.
- Memory management: The CLR manages the allocation and deallocation of memory for managed objects. It also performs garbage collection to reclaim the memory used by objects that are no longer needed.
- Exception handling: The CLR provides a mechanism for handling exceptions that are thrown during the execution of managed code. It also provides a way to catch and handle exceptions in a structured and consistent way.
- Security: The CLR provides a security model that helps to protect against malicious code and enforce security policies. It also provides support for code access security and role-based security.
The CLR is an important component of the .NET Framework, and it provides many services and features that are used by .NET applications.
What is a managed code?
Managed code is code that is written in a .NET-supported programming language and executed by the Common Language Runtime (CLR). The CLR is the execution engine of the .NET Framework, and it is responsible for executing managed code and providing services to the code, such as memory management, security, and exception handling.
Managed code is compiled into an intermediate language (IL) and then executed by the CLR using a Just-In-Time (JIT) compiler. The JIT compiler converts the IL into machine code that can be executed by the processor.
Managed code is contrasted with native code, which is code that is compiled directly into machine code and executed by the processor. Native code is not managed by the CLR and does not have access to the services provided by the CLR.
Managed code has several advantages over native code, for example:
- Language independence: Managed code can be written in any .NET-supported programming language and executed by the CLR. This allows you to choose the language that is best suited for your needs.
- Memory management: The CLR manages the allocation and deallocation of memory for managed objects, which helps to prevent memory leaks and other memory-related issues.
- Exception handling: The CLR provides a mechanism for handling exceptions that are thrown during the execution of managed code. This allows you to catch and handle exceptions in a structured and consistent way.
- Security: The CLR provides a security model that helps to protect against malicious code and enforce security policies. It also provides support for code access security and role-based security.
What is a namespace in .NET?
In .NET, a namespace is a logical container for types, such as classes, interfaces, and structs. It is used to organize and group related types, and to prevent naming conflicts between types with the same name. A namespace is declared using the namespace
keyword, followed by the namespace name.
What is an assembly in .NET?
In .NET, an assembly is a unit of deployment, versioning, and reuse of code. It is a logical container for types, resources, and metadata, and it can be a single file or a collection of files.
An assembly can contain one or more types, such as classes, interfaces, and structs. It can also contain resources, such as images, text files, and configuration files. The assembly also contains metadata, which is data that describes the assembly and its contents.
There are two types of assemblies in .NET:
- Private assemblies: Private assemblies are used by a single application and are deployed with the application. They are stored in the application’s installation directory or in a subdirectory.
- Shared assemblies: Shared assemblies are used by multiple applications and are deployed to the global assembly cache (GAC). The GAC is a central repository of shared assemblies that is available to all applications on the computer.
Assemblies are an important part of .NET programming, as they provide a way to package and reuse code, and to version and deploy code. They also provide a way to create modular applications that can be composed of multiple independent components.
What is a strong name in .NET?
A strong name is a unique identifier that is used to identify a .NET assembly. It consists of the assembly’s name, version, culture, and public key token.
A strong name is created using the strong name utility (sn.exe
) and a public/private key pair. The public key is used to sign the assembly, and the private key is used to create the strong name.
A strong name ensures that an assembly can be uniquely identified, even if multiple versions of the assembly are deployed on the same computer. It also ensures that the assembly has not been tampered with, as any changes to the assembly will invalidate the strong name.
To use a strong-named assembly, you must specify the assembly’s strong name in the reference to the assembly. For example:
<Reference Include="MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
Strong names are an important part of .NET programming, as they provide a way to uniquely identify assemblies and ensure their integrity. They are used to prevent versioning conflicts and to enable side-by-side deployment of multiple versions of the same assembly.
What is reflection in .NET?
Reflection is a feature in .NET that allows you to inspect and manipulate types at runtime. It is a way to examine and modify the characteristics of types, such as their properties, methods, and attributes.
To use reflection, you can use the System.Reflection
namespace, which provides classes and interfaces for working with types at runtime.
Here is an example of using reflection to get the properties of a type:
Type type = typeof(MyClass);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.Name);
}
This code gets the Type
object for the MyClass
type, and then uses the GetProperties
method to get an array of PropertyInfo
objects that represent the properties of the type. It then iterates through the array and writes the names of the properties to the console.
You can also use reflection to invoke methods and set or get property values. For example:
Type type = typeof(MyClass);
object obj = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("DoSomething");
method.Invoke(obj, null);
PropertyInfo property = type.GetProperty("MyProperty");
property.SetValue(obj, 123);
Web API:
What is the difference between a Web API and a Web Service?
Web API and Web Service are two technologies that are used to build distributed applications over the Internet. Both technologies allow you to create applications that can communicate with other applications and exchange data. However, there are some differences between the two technologies:
- Protocol: Web API uses HTTP as the communication protocol, while Web Service can use a variety of protocols, such as HTTP, SOAP, and XML-RPC.
- Data format: Web API uses a variety of data formats, such as JSON and XML, while Web Service uses XML as the primary data format.
- Architecture: Web API is based on a RESTful architecture, which is based on HTTP verbs and the uniform resource identifier (URI) of the resource being accessed. Web Service is based on a remote procedure call (RPC) architecture, which is based on calling methods on a remote server.
- Use cases: Web API is typically used for building APIs for web and mobile applications, while Web Service is used for building more traditional service-oriented applications.
Overall, Web API is a more modern and flexible technology for building distributed applications, while Web Service is a more traditional and specialized technology.
What is attribute routing in Web API?
Attribute routing is a feature in Web API that allows you to specify the route for an action using attributes. It is an alternative to the conventional route-by-convention approach, where the route is determined based on the naming conventions of the controllers and actions.
To use attribute routing in Web API, you can decorate the actions with the Route
attribute, and specify the route template as an argument. For example:
[Route("api/customers/{id}")]
public Customer GetCustomer(int id)
{
// Return the customer with the specified id
}
In this example, the GetCustomer
action is decorated with the Route
attribute, and the route template specifies that the action can be accessed at the /api/customers/{id}
URL, where {id}
is a placeholder for the customer id.
You can also use the RoutePrefix
attribute to specify a route prefix for a controller, which will be applied to all the actions in the controller. For example:
[RoutePrefix("api/customers")]
public class CustomersController : ApiController
{
[Route("{id}")]
public Customer GetCustomer(int id)
{
// Return the customer with the specified id
}
}
In this example, the CustomersController
class is decorated with the RoutePrefix
attribute, and the GetCustomer
action is decorated with the Route
attribute. The combined route template for the action will be /api/customers/{id}
.
Attribute routing is a useful feature in Web API, as it allows you to have more control over the routes of your actions, and to specify more complex and flexible route templates.
What is a model binding in Web API?
Model binding is a feature in Web API that allows you to map HTTP request data to action method parameters. It is a way to automaticaly convert the request data to the required data type and pass it to the action method as an argument.
To use model binding in Web API, you can specify the parameter name and data type of the action method, and decorate the parameter with the appropriate model binder attribute. For example:
[HttpPost]
public HttpResponseMessage Post([FromBody] MyData data)
{
// Do something with the data
return Request.CreateResponse(HttpStatusCode.OK);
}
In this example, the Post
action has a single parameter of type MyData
, which is decorated with the FromBody
attribute. The model binder will automatically bind the request body to the MyData
parameter, and pass it to the action method.
You can also use model binding to bind request data from other sources, such as the query string, the form data, and the route values. For example:
[HttpGet]
public HttpResponseMessage Get(int id, [FromUri] MyData data)
{
// Do something with the id and data
return Request.CreateResponse(HttpStatusCode.OK);
}
In this example, the Get
action has two parameters: an id
parameter and a data
parameter. The id
parameter is bound from the route value, while the data
parameter is bound from the query string. The model binder will automatically convert the request data to the required data types and pass them to the action method as arguments.
What is a media type formatter in Web API?
A media type formatter is a class in Web API that is responsible for serializing and deserializing HTTP request and response data. It is used to convert the data to and from the format that is required by the client and the server.
Web API supports a variety of media types, such as JSON, XML, and HTML, and you can use media type formatters to handle these types. The framework includes built-in media type formatters for handling common media types, and you can also create custom media type formatters for handling other types.
To use a media type formatter in Web API, you can specify the media type in the Accept
and Content-Type
headers of the request and response. The framework will then use the appropriate formatter to serialize or deserialize the data.
Here is an example of using the built-in JSON media type formatter to send and receive data in a Web API action:
[HttpPost]
public HttpResponseMessage Post([FromBody] MyData data)
{
// Do something with the data
return Request.CreateResponse(HttpStatusCode.OK, data);
}
In this example, the Post
action receives a MyData
object as the request body, and returns the object in the response body. The formatter will serialize and deserialize the MyData
object to and from JSON format.
Media type formatters are an important part of Web API, as they allow you to easily send and receive data in a variety of formats, and to support different media types in your API.
What is dependency injection in Web API?
Dependency injection is a design pattern that is used to decouple components in a system. It is a way to provide a component with its dependencies, rather than hardcoding them within the component.
In Web API, dependency injection is used to provide components, such as controllers and services, with their dependencies. This allows you to write more flexible and testable code, as the components can be easily unit tested in isolation.
To use dependency injection in Web API, you can use a dependency injection container, such as Microsoft.Extensions.DependencyInjection. The container is responsible for creating and managing the dependencies for the components in the application.
Here is an example of how to use dependency injection in a Web API controller:
public class MyController : ApiController
{
private readonly IMyService _service;
public MyController(IMyService service)
{
_service = service;
}
[HttpGet]
public IHttpActionResult Get()
{
var result = _service.GetData();
return Ok(result);
}
}
In this example, the MyController
class has a dependency on the IMyService
interface. The dependency is provided through the constructor, and the controller can use the service to perform its tasks.
To configure the dependency injection container, you can use the ConfigureServices
method in the Startup
class. For example:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
services.AddControllers();
}
This code adds the IMyService
interface and the MyService
class to the dependency injection container, and specifies that a new instance of the MyService
class should be created every time it is requested.
Dependency injection is a useful pattern for building Web API applications, as it allows you to write more flexible and testable code, and to easily manage the dependencies of the components in the application.
For more questions answers like this; you can also follow this profile – https://dev.to/asifbuetcse