.NET Questions I Flashcards
What is .NET?
.NET is a comprehensive development platform used for building a wide variety of applications, including web, mobile, desktop, and gaming. It supports multiple programming languages, such as C#, F#, and Visual Basic.
.NET provides a large class library called Framework Class Library (FCL) and runs on a Common Language Runtime (CLR) which offers services like memory management, security, and exception handling.
Can you explain the Common Language Runtime (CLR)?
The CLR is a virtual machine component of the .NET framework that manages the execution of .NET programs.
It provides important services such as memory management, type safety, exception handling, garbage collection, and thread management.
The CLR converts Intermediate Language (IL) code into native machine code through a process called Just-In-Time (JIT) compilation.
This ensures that .NET applications can run on any device or platform that supports the .NET framework.
What is the difference between managed and unmanaged code?
Managed code is executed by the CLR, which provides services like garbage collection, exception handling, and type checking. It’s called “managed” because the CLR manages a lot of the functionalities that developers would otherwise need to implement themselves.
Unmanaged code, on the other hand, is executed directly by the operating system, and all memory allocation, type safety, and security must be handled by the programmer. Examples of unmanaged code include applications written in C or C++.
Explain the basic structure of a C# program.
Answer: A basic C# program consists of the following elements:
Namespace declaration: A way to organize code and control the scope of classes and methods in larger projects.
Class declaration: Defines a new type with data members (fields, properties) and function members (methods, constructors).
Main method: The entry point for the program where execution begins and ends.
Statements and expressions: Perform actions with variables, calling methods, looping through collections, etc.
What are Value Types and Reference Types in C#?
In C#, data types are divided into two categories: Value Types and Reference Types.
This distinction affects how values are stored and manipulated within memory.
Value Types: Store data directly and are allocated on the stack. This means that when you assign one value type to another, a direct copy of the value is created. Basic data types (int, double, bool, etc.) and structs are examples of value types. Operations on value types are generally faster due to stack allocation.
Reference Types: Store a reference (or pointer) to the actual data, which is allocated on the heap. When you assign one reference type to another, both refer to the same object in memory; changes made through one reference are reflected in the other. Classes, arrays, delegates, and strings are examples of reference types.
What is garbage collection in .NET?
Garbage collection (GC) in .NET is an automatic memory management feature that frees up memory used by objects that are no longer accessible in the program.
It eliminates the need for developers to manually release memory, thereby reducing memory leaks and other memory-related errors.
The GC operates on a separate thread and works in three phases: marking, relocating, and compacting.
During the marking phase, it identifies which objects in the heap are still in use.
During the relocating phase, it updates the references to objects that will be compacted.
Finally, during the compacting phase, it reclaims the space occupied by the garbage objects and compacts the remaining objects to make memory allocation more efficient.
Explain the concept of exception handling in C#.
Exception handling in C# is a mechanism to handle runtime errors, allowing a program to continue running or fail gracefully instead of crashing. It is done using the try, catch, and finally blocks. The try block contains code that might throw an exception, while catch blocks are used to handle the exception. The finally block contains code that is executed whether an exception is thrown or not, often for cleanup purposes.
What are the different types of classes in C#?
In C#, classes can be categorized based on their functionality and accessibility:
-> Static classes: Cannot be instantiated and can only contain static members.
-> Sealed classes: Cannot be inherited from.
-> Abstract classes: Cannot be instantiated and are meant to be inherited from.
-> Partial classes: Allow the splitting of a class definition across multiple files.
-> Generic classes: Allow the definition of classes with placeholders for the type of its fields, methods, parameters, etc.
Each type serves different purposes in the context of object-oriented programming and design patterns.
Can you describe what a namespace is and how it is used in C#?
A namespace in C# is used to organize code into a hierarchical structure.
It allows the grouping of logically related classes, structs, interfaces, enums, and delegates.
Namespaces help avoid naming conflicts by qualifying the uniqueness of each type. For example, the System namespace in .NET includes classes for basic system operations, such as console input/output, file reading/writing, and data manipulation.
What is encapsulation?
Encapsulation is a fundamental principle of object-oriented programming (OOP) that involves bundling the data (attributes) and methods (operations) that operate on the data into a single unit, or class, and restricting access to the internals of that class.
This is typically achieved through the use of access modifiers such as private, public, protected, and internal.
Encapsulation helps to protect an object’s internal state from unauthorized access and modification by external code, promoting data integrity and security.
Encapsulation allows the internal representation of an object to be hidden from the outside, only allowing access through a public interface. This concept is also known as data hiding. By controlling how data is accessed and modified, encapsulation helps to reduce complexity and increase reusability of code.
Explain polymorphism and its types in C#.
Polymorphism is a core concept in object-oriented programming (OOP) that allows objects to be treated as instances of their parent class rather than their actual derived class. This enables methods to perform different tasks based on the object that invokes them, enhancing flexibility and enabling code reusability. In C#, polymorphism can be implemented in two ways: static (compile-time) polymorphism and dynamic (runtime) polymorphism.
Static Polymorphism: Achieved through method overloading and operator overloading. It allows multiple methods or operators with the same name but different parameters to coexist, with the specific method or operator being invoked determined at compile time based on the arguments passed.
Dynamic Polymorphism: Achieved through method overriding. It allows a method in a derived class to have the same name and signature as a method in its base class, but with different implementation details. The method that gets executed is determined at runtime, depending on the type of the object.
What are delegates and how are they used in C#?
Delegates in C# are type-safe function pointers or references to methods with a specific parameter list and return type.
They allow methods to be passed as parameters, stored in variables, and returned by other methods, which enables flexible and extensible programming designs such as event handling and callback methods.
Delegates are particularly useful in implementing the observer pattern and designing frameworks or components that need to notify other objects about events or changes without knowing the specifics of those objects.
There are three main types of delegates in C#:
-> Single-cast delegates: Point to a single method at a time.
-> Multicast delegates: Can point to multiple methods on a single invocation list.
-> Anonymous methods/Lambda expressions: Allow inline methods or lambda expressions to be used wherever a delegate is expected.
Describe what LINQ is and give an example of where it might be used.
LINQ (Language Integrated Query) is a powerful feature in C# that allows developers to write expressive, readable code to query and manipulate data.
It provides a uniform way to query various data sources, such as collections in memory, databases (via LINQ to SQL, LINQ to Entities), XML documents (LINQ to XML), and more.
LINQ queries offer three main benefits: they are strongly typed, offer compile-time checking, and support IntelliSense, which enhances developer productivity and code maintainability.
LINQ can be used in a variety of scenarios, including filtering, sorting, and grouping data. It supports both method syntax and query syntax, providing flexibility in how queries are expressed.
What is the difference between an abstract class and an interface?
In C#, both abstract classes and interfaces are types that enable polymorphism, allowing objects of different classes to be treated as objects of a common super class. However, they serve different purposes and have different rules:
Abstract Class:
-Can contain implementation of methods, properties, fields, or events.
-Can have access modifiers (public, protected, etc.).
-A class can inherit from only one abstract class (single inheritance).
-Can contain constructors.
-Used when different implementations of objects have common methods or properties that can share a common implementation.
____________________________________________________
Interface:
-Cannot contain implementations, only declarations of methods, properties, events, or indexers.
-Members of an interface are implicitly public.
-A class or struct can implement multiple interfaces (multiple inheritance).
-Cannot contain fields or constructors.
-Used to define a contract for classes without imposing inheritance hierarchies.
How do you manage memory in .NET applications?
Memory management in .NET applications is primarily handled automatically by the Garbage Collector (GC), which provides a high-level abstraction for memory allocation and deallocation, ensuring that developers do not need to manually free memory. However, understanding and cooperating with the GC can help improve your application’s performance and memory usage. Here are key aspects of memory management in .NET:
Garbage Collection: Automatically reclaims memory occupied by unreachable objects, freeing developers from manually deallocating memory and helping to avoid memory leaks.
Dispose Pattern: Implementing the IDisposable interface and the Dispose method allows for the cleanup of unmanaged resources (such as file handles, database connections, etc.) that the GC cannot reclaim automatically.
Finalizers: Can be defined in classes to perform cleanup operations before the object is collected by the GC. However, overuse of finalizers can negatively impact performance, as it makes objects live longer than necessary.
Using Statements: A syntactic sugar for calling Dispose on IDisposable objects, ensuring that resources are freed as soon as they are no longer needed, even if exceptions are thrown.
Large Object Heap (LOH) Management: Large objects are allocated on a separate heap, and knowing how to manage large object allocations can help reduce memory fragmentation and improve performance.
Explain the concept of threading in .NET.
Threading in .NET allows for the execution of multiple operations simultaneously within the same process.
It enables applications to perform background tasks, UI responsiveness, and parallel computations, improving overall application performance and efficiency. The .NET framework provides several ways to create and manage threads:
System.Threading.Thread: A low-level approach to create and manage threads directly. This class offers fine-grained control over thread behavior.
ThreadPool: A collection of worker threads maintained by the .NET runtime, offering efficient execution of short-lived background tasks without the overhead of creating individual threads for each task.
Task Parallel Library (TPL): Provides a higher-level abstraction over threading, using tasks that represent asynchronous operations. TPL uses the ThreadPool internally and supports features like task chaining, cancellation, and continuation.
async and await: Keywords that simplify asynchronous programming, making it easier to write asynchronous code that’s as straightforward as synchronous code.
What is async/await and how does it work?
**The async modifier indicates that a method is asynchronous **and may contain one or more await expressions. The await keyword is applied to a task, indicating that the method should pause until the awaited task completes, allowing other operations to run concurrently without blocking the main thread.
Key points about async/await:
-Improves application responsiveness, particularly important for UI applications where long-running operations can freeze the user interface.
-Enables server applications to handle more concurrent requests by freeing up threads while waiting for operations to complete.
-Simplifies error handling in asynchronous code with try-catch blocks.
Describe the Entity Framework and its advantages.
Entity Framework (EF) is an open-source object-relational mapping (ORM) framework for .NET. It enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers usually need to write.
Entity Framework provides a high-level abstraction over database connections and operations, allowing developers to perform CRUD (Create, Read, Update, Delete) operations without having to deal with the underlying database SQL commands directly.
Advantages of using Entity Framework include:
-Increased Productivity: Automatically generates classes based on database schemas, reducing the amount of manual coding required for data access.
-Maintainability: Changes to the database schema can be easily propagated to the code through migrations, helping maintain code and database schema synchronicity.
-Support for LINQ: Enables developers to use LINQ queries to access and manipulate data, providing a type-safe way to query databases that integrates with the C# language.
-Database Agnostic: EF can work with various databases, including SQL Server, MySQL, Oracle, and more, by changing the database provider with minimal changes to the code.
-Caching, Lazy Loading, Eager Loading: Offers built-in support for caching, and configurable loading options like lazy loading and eager loading, improving application performance.
What are extension methods and where would you use them?
Extension methods in C# allow developers to add new methods to existing types without modifying, deriving from, or recompiling the original types. They are static methods defined in a static class, but called as if they were instance methods on the extended type. Extension methods provide a flexible way to extend the functionality of a class or interface.
To use extension methods, the static class containing the extension method must be in scope, which usually requires a using directive for the namespace of the class.
Advantages of using extension methods include:
-> Enhancing the functionality of third-party libraries or built-in .NET types without access to the original source code.
-> Keeping code cleaner and more readable by encapsulating complex operations into methods.
-> Facilitating a fluent interface style of coding, which can make code more expressive.
How do you handle exceptions in a method that returns a Task?
In asynchronous programming with C#, when a method returns a Task or Task<T>, exceptions should be handled within the task to avoid unhandled exceptions that can crash the application. Exceptions thrown in a task are captured and placed on the returned task object. To handle these exceptions, you can use a try-catch block within the asynchronous method, or you can inspect the task after it has completed for any exceptions.</T>
What is reflection in .NET and how would you use it?
Reflection in .NET is a powerful feature that allows runtime inspection of assemblies, types, and their members (such as methods, fields, properties, and events).
It enables creating instances of types, invoking methods, and accessing fields and properties dynamically, without knowing the types at compile time.
Reflection is used for various purposes, including building type browsers, dynamically invoking methods, and reading custom attributes.
Reflection can be particularly useful in scenarios such as:
-> Dynamically loading and using assemblies.
-> Implementing object browsers or debuggers.
-> Creating instances of types for dependency injection frameworks.
-> Accessing and manipulating metadata for assemblies and types.
Concept of middleware in ASP.NET Core?
Middleware in ASP.NET Core is software that’s assembled into an application pipeline to handle requests and responses. Each component in the middleware pipeline is responsible for invoking the next component in the sequence or short-circuiting the chain if necessary.
Middleware components can perform a variety of tasks, such as authentication, routing, session management, and logging.
Middleware enables you to customize the request pipeline in ways that are most suited to your application’s needs. They are executed in the order they are added to the pipeline, allowing for precise control over how requests are processed and how responses are constructed.