.NET Questions I Flashcards

1
Q

What is .NET?

A

.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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can you explain the Common Language Runtime (CLR)?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between managed and unmanaged code?

A

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++.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the basic structure of a C# program.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are Value Types and Reference Types in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is garbage collection in .NET?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Explain the concept of exception handling in C#.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the different types of classes in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Can you describe what a namespace is and how it is used in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is encapsulation?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain polymorphism and its types in C#.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are delegates and how are they used in C#?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Describe what LINQ is and give an example of where it might be used.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you manage memory in .NET applications?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Explain the concept of threading in .NET.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is async/await and how does it work?

A

**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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Describe the Entity Framework and its advantages.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are extension methods and where would you use them?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you handle exceptions in a method that returns a Task?

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is reflection in .NET and how would you use it?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Concept of middleware in ASP.NET Core?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Describe the Dependency Injection (DI) pattern and how it’s implemented in .NET Core.

A

Dependency Injection (DI) is a design pattern that facilitates loose coupling between software components by removing the direct dependencies among them.

Instead of instantiating dependencies directly, components receive their dependencies from an external source (often an inversion of control container). DI makes your code more modular, easier to test, maintain, and extend.

.NET Core has built-in support for dependency injection, which allows services to be registered and resolved through an IoC (Inversion of Control) container. The container manages object creation and injects dependencies where required. This mechanism is central to ASP.NET Core applications, enabling features like middleware, controllers, views, and other services to be provided and managed by the framework.

The core concepts in .NET Core’s DI system include:

-> Service registration: Services are registered with the DI container, typically in the Startup.ConfigureServices method, specifying their lifetime (singleton, scoped, or transient).

->Service resolution: Services are resolved either through constructor injection, method call injection, or property injection, with constructor injection being the most common approach.

24
Q

What is the purpose of the .NET Standard?

A

The .NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET implementations.

The goal of the .NET Standard is to establish greater uniformity in the .NET ecosystem. It enables developers to create libraries that are compatible across different .NET platforms, such as .NET Core, .NET Framework, Xamarin, and others, with a single codebase. This simplifies the development process and enhances code reuse across projects and platforms.

The .NET Standard is versioned, with each version building upon the previous one and adding more APIs. Higher versions of the .NET Standard support newer APIs but reduce the number of platforms that support that standard because older platforms may not implement the newer APIs.

25
Q

Explain the differences between .NET Core, .NET Framework, and Xamarin.

A

.NET Core, .NET Framework, and Xamarin are all part of the .NET ecosystem, but they serve different purposes and are used in different types of projects. Understanding the differences between them can help you choose the right technology for your specific needs.

.NET Framework:

The original .NET implementation, launched in 2002.
Primarily runs on Windows and is used for developing Windows desktop applications and ASP.NET web applications.
Provides a vast library of pre-built functionality, including Windows Forms, WPF (Windows Presentation Foundation) for desktop applications, and ASP.NET for web applications.
Moving forward, it will receive only critical security updates and bug fixes.

.NET Core:
A cross-platform, open-source reimplementation of .NET that runs on Windows, macOS, and Linux.
Designed to be modular and lightweight, making it suitable for web applications, microservices, and cloud applications.
Supports development of console applications, ASP.NET Core web applications, and libraries.
With the release of .NET 5 and beyond, .NET Core has evolved into simply “.NET,” unifying the .NET platform and serving as the future of the .NET ecosystem.

Xamarin:
A .NET platform for building mobile applications that can run on iOS, Android, and Windows devices.
Allows developers to write mobile applications using C# and .NET libraries while providing native performance and look-and-feel on each platform.
Integrates with Visual Studio, providing a rich development environment.
Xamarin.Forms allows for the creation of UIs from a single, shared codebase, while Xamarin.iOS and Xamarin.Android provide access to platform-specific APIs.

26
Q

How does garbage collection work in .NET and how can you optimize it?

A

Garbage Collection (GC) in .NET is an automatic memory management feature that helps in reclaiming the memory used by objects that are no longer accessible in the application. It eliminates the need for manual memory management, reducing the risks of memory leaks and other memory-related issues.

How Garbage Collection Works:

Mark: The GC traverses the object graph to mark objects that are reachable, starting from root references. Reachable objects are considered “live”.

Compact: To reclaim the memory occupied by unreachable objects, the GC compacts the remaining objects, thus reducing the space used on the managed heap and making room for new objects.

Generations: The GC uses a generational approach to manage memory collections, dividing the heap into three generations (0, 1, and 2) for more efficient garbage collection.

Generation 0 is for short-lived objects,

Generation 1 for medium-lived objects,

Generation 2 for long-lived objects.

Collecting younger generations more frequently reduces the need to perform expensive collections on older generations.

27
Q

What are attributes in C# and how can they be used?

A

Attributes in C# are a powerful way to add declarative information to your code. They are used to add metadata, such as compiler instructions, annotations, or custom information, to program elements (classes, methods, properties, etc.). Attributes can influence the behavior of certain components at runtime or compile time, and they can be queried through reflection.

Common Uses of Attributes:

-> Marking methods as test methods in a unit testing framework (e.g., [TestMethod] in MSTest).
-> Specifying serialization rules (e.g., [Serializable], [DataMember]).
-> Controlling binding and model validation in ASP.NET Core (e.g.,** [Required]**, [Bind]).
-> Defining aspects of web service behaviors (e.g., [WebMethod]).
-> Custom attributes for domain-specific purposes.

28
Q

Can you describe the process of code compilation in .NET?

A

The process of code compilation in .NET involves converting high-level code (such as C#) into a platform-independent Intermediate Language (IL) and then into platform-specific machine code. This process is facilitated by the .NET Compiler Platform (“Roslyn” for C# and Visual Basic) and the Common Language Runtime (CLR). Here’s an overview of the steps involved:

Source Code to Intermediate Language (IL):

When you compile a .NET application, the .NET compiler for your language (e.g., csc.exe for C#) compiles the source code into Intermediate Language (IL). IL is a CPU-independent set of instructions that can be efficiently converted into native machine code.
Along with IL, metadata is generated, which includes information about the types, members, references, and other data that the IL code uses.

IL to Native Code:

At runtime, the .NET application is executed by the CLR. The** CLR’s Just-In-Time (JIT)** compiler converts the IL code into native machine code specific to the architecture of the target machine.

This conversion happens on a need-to-run basis; that is, each method’s IL is converted to native code the first time the method is called. The native code is then cached, so subsequent calls to the same method do not require re-compilation.

Execution:

The native code is executed directly by the hardware of the target machine, leading to the execution of the .NET application.

29
Q

Aspects of .NET Compilation:

A

Assembly: The compiled code and resources are packed into assemblies (.dll or .exe files), which are the units of deployment and versioning in .NET. Assemblies contain the IL code and metadata.

Metadata: Metadata describes the assembly itself and the types defined within the assembly, including their methods and properties. This information is used by the CLR during execution and supports features like reflection.

+ files

Strong Naming and GAC: Assemblies can be strong-named to ensure their uniqueness and integrity. Strong-named assemblies can be placed in the Global Assembly Cache (GAC) for shared use by multiple applications.

30
Q

What is the Global Assembly Cache (GAC) and when should it be used?

A

The Global Assembly Cache (GAC) is a machine-wide code cache for the Common Language Runtime (CLR) in the .NET Framework.

It stores assemblies specifically designated to be shared by several applications on the computer.

The GAC is used to store shared .NET assemblies that have strong names (which are unique identifiers consisting of a name, version number, culture information, and a public key token).

Key Points about the GAC:

Sharing Assemblies: The GAC allows multiple applications to share the same library, reducing memory usage and ensuring consistency across applications that use common components.

Strong Naming: Only assemblies with strong names (signed with a public/private key pair) can be added to the GAC. Strong naming guarantees the uniqueness of the assembly’s identity, allowing side-by-side hosting of different versions.

Versioning: The GAC supports side-by-side execution of different versions of the same assembly. This enables applications to specify and use the version of an assembly they were built with, even if newer versions are installed on the system.

31
Q

How would you secure a web application in ASP.NET Core?

A

Authentication and Authorization:
Data Protection:
Cross-Site Scripting (XSS) Prevention:
Cross-Site Request Forgery (CSRF) Protection:
Security Headers:
Dependency Management:
Logging and Monitoring:
Secure Deployment

32
Q

What is C# and what are its key features?

A

C#, pronounced “C-sharp,” is an object-oriented, multi-paradigm programming language developed by Microsoft as part of its .NET initiative. It’s widely used for developing applications targeting the Windows ecosystem.

Simplicity: C# streamlines complex tasks, making common programming patterns more manageable.

Type Safety: It employs a robust type system that mitigates many common programming errors at compile time.

Object-Oriented Design: It encourages modular, reusable code structures through classes and interfaces.

Scalability: C# supports both small, quick programs and large, intricate applications.

Cross-Language Support: It integrates seamlessly with other languages in the .NET ecosystem, offering advantages such as unified debugging and code reuse.

Language Interoperability: Developers can leverage code from other languages integrated into .NET.

Memory Management: It uses automatic memory management, reducing the burden of manual memory allocation and deallocation.

Asynchronous Programming: C# provides powerful tools to create responsive applications, such as the async and await keywords.

Integrated Development Environment (IDE): Visual Studio is a robust and popular tool for C# development, offering features like IntelliSense and debugging.

Library Support: C# is backed by a vast standard library that simplifies various tasks.

Modern Features: C# continues to evolve, leveraging contemporary software development concepts and practices.

Suitability for Web Development: C# is used in conjunction with ASP.NET for developing dynamic web applications and services.

LINQ (Language-Integrated Query): C# provides LINQ, enabling developers to query collections akin to SQL.

Built-In Security Features: C# includes functionalities such as Code Access Security (CAS) and Role-Based Security.

Native Code Execution: C# applications are executed through the Common Language Runtime (CLR), offering platform independence.

Exception Handling: It utilizes a structured error-handling approach, making it easier to reason about potential code issues.

Polymorphism and Inheritance: These essential object-oriented concepts are foundational to C#.

33
Q

Memory Management in C#

A

C# uses the Garbage Collector (GC) for automatic memory management. The GC identifies and removes objects that are no longer in use, optimizing memory consumption. However, improper memory handling can lead to memory leaks or inefficient GC performance, underscoring the need for developer awareness.

34
Q

Strong Types in C#

A

One of the defining characteristics of C# is its strong type system. It enforces type checking at compile time, reducing the likelihood of data-related errors. This stringency extends to both primitive types (e.g., int, float, bool) and user-defined types. C# 7.0 onward introduced “pattern matching”, enhancing the language’s handling of types and enabling straightforward type-based operations.

35
Q

Asynchronous Programming Support

A

C# incorporates a task-based model for efficient asynchronous execution. This approach, facilitated by the async and await keywords, mitigates thread-related overhead typically associated with multithreading, bolstering application performance.

36
Q

Code Access Security

A

Historically, C# applications implemented Code Access Security (CAS). This feature defined and enforced permissions for varying levels of privilege within an application. CAS has been gradually phased out in newer versions of .NET, but C# remains renowned for its robust security features.

37
Q

What are the different types of data types available in C#?

A

C# features a variety of data types, each tailored to specific data needs. These types are grouped under different categories that include:

Value Types: They store their own data and are distinct from one another. Examples include basic types like int and float, as well as struct.

Reference Types: These types store references to their data. Classes, arrays, and delegates are classic examples.

Integral Types: These are whole numbers, either signed or unsigned.

Floating-Point Types: These accommodate non-integer numbers.

High-Precision Decimal Type: Ideal for precise monetary and scientific calculations.

Boolean Type: Represents truth values.

Character Types: Specifically designed for holding characters and described in two flavors: Uniocode and ASCII.

Text Types: Specifically tailored for text like strings.

38
Q

Other Types, meaning of dll

A

struct, enum, Nullable, tuple, valueTuple are among other types in C#.

.dll (Dynamic Link Library) to plik biblioteki dynamicznej używany w systemie Windows. Jest to jeden z kluczowych elementów architektury aplikacji Windows i umożliwia programom dzielenie się kodem oraz zasobami. Pliki .dll mogą zawierać różnorodne funkcje, zasoby, dane i inne komponenty,

39
Q

What is the difference between value types and reference types?

A

Data Storage
Value Types: Store the data in their memory space. Examples include primitive types like integers and floating-point numbers.

Reference Types: Store a reference to the data, which resides in the managed heap, and have dynamic storage size.

Memory Management
Value Types: Managed by the stack. Memory is allocated and deallocated automatically within the scope of where they are defined.

Reference Types: Managed by the heap. Garbage Collector automatically allocates memory and reclaims it when the object is no longer referenced.

Assignment Behavior
Value Types: Directly manipulate their allocated memory. Assigning one value type to another creates an independent copy.

Reference Types: Store a reference to the object’s location in memory. Assigning a reference type to another only creates a new reference to the same object in memory.

Performance
Value Types: Generally faster to access and manipulate because of their stack-based memory management. Ideal for smaller data types.

Reference Types: Slight performance overhead due to indirection (pointer dereferencing) when accessing data in heap memory.

Nullability
Value Types: Cannot be null. They always have a defined value.
Reference Types: Can be null, especially if it’s not been assigned an object.

Type Categories
Value Types: Most primitive data types (int, float, bool, char, etc.), enums, and structs are value types.

Reference Types: Classes, arrays, strings, delegates, and objects of types that are derived from the base type object are reference types.

40
Q

What are nullable types in C#?

A

Nullable types are a special data type in C# that can represent both a regular value and null. It is a beneficial feature for representing data that might be absent or unknown.

Key Considerations for Using Nullable Types
Memory Consumption: Data types with explicit sizes, such as int or bool, need more space in memory when converted to nullable types.

Performance: Nullable types might result in fewer optimizations, particularly with certain operations.

Clarity: They offer transparency about the possible absence of a value.

The “null-conditional” operators
In C#, there are dedicated “null-conditional” operators caters to appropriately performing actions for nullable types, ensuring that there is no NullReferenceException. Among these are ?., ??, ??=, and ?.[].

41
Q

Can you describe what namespaces are and how they are used in C#?

A

A key concept in C#, a namespace organizes code, allows for better code management, and prevents naming conflicts between different elements (such as classes, interfaces, and enums).

Namespaces are particularly useful in larger projects and team-based development.

Key Features

Granularity: Namespaces provide a way to group related pieces of code, making it easier to navigate your codebase.

Uniqueness: Every element in a namespace is guaranteed to have a unique name.

Accessibility Control: By default, members in a namespace are accessible only within the same namespace. You can use public and internal access modifiers to control this.

42
Q

Common Built-In .NET Namespaces

A

System: Fundamental types and base types.
System.Collections: Implementations of standard collection classes (like lists, dictionaries, and queues).
System.IO: Input and output, including file operations.
System.Linq: Language Integrated Query (LINQ) functionality.

43
Q

Common Namespaces

A

System.Data: Managed code for accessing data from relational data sources.
System.Threading: Enables multi-threading in applications.
System.Xml: Provides support for processing XML.

44
Q

Explain the concept of boxing and unboxing in C#.

A

Boxing is the process of converting a value type (struct) to a reference type (object) so it can be assigned to a variable of type object or an interface. Conversely, unboxing is the reverse operation.

Boxing: When a value type is assigned to an object-typed variable or when it’s passed as a method argument that expects an object or an interface type, the CLR boxes the value type, creating a reference-type object that holds the value.

Unboxing: The CLR extracts the original value type from the object, provided the object actually contains such a value. A runtime error occurs if the object holds a different type.

45
Q

Explain the concept of boxing and unboxing in C# performance

A

Performance: Boxing and unboxing involve overhead due to memory allocation (when boxing) and type checks during unboxing. They are, therefore, less efficient than direct interactions with value types.

Garbage Collection: More aggressive memory management for short-lived objects could be necessary since boxed objects reside on the heap, subject to Garbage Collection.

Potential for Errors: Unboxing operations might fail with an InvalidCastException if the object’s type doesn’t match the expected value type.

Type Mismatch: There’s a risk of unexpected behavior if types get mixed up, especially when unboxing.

46
Q

What is Type Casting and what are its types in C#?

A

Type casting, in the context of C#, refers to the explicit and implicit conversion of data types. While explicit casting might lead to data loss, implicit casting is carried out by the C# compiler, ensuring safe conversion.

________________________________________________

Implicit Casting
This form of casting is automatic and occurs when there is no risk of data loss. For instance, an int can be automatically cast to a long as there is no possibility of truncation.

__________________________________________________

Explicit Casting
This form of casting must be done manually and is necessary when there is a risk of data loss. For example, when converting a double to an int, data loss due to truncation could occur. C# requires you to explicitly indicate such conversion, and if the conversion is not possible, it throws a System.InvalidCastException.

47
Q

As operand and is operand

A

Using as Operand
If you are sure that an object can be cast to a specific type, use the as operand for optimization. If the conversion is possible, the operand returns an object of the specified type; otherwise, it returns null.

The is Operator for Type Checking
With the is operator, you can test whether an object is compatible with a specific type. This tool is very useful to prevent InvalidCastException errors.

48
Q

What is the difference between == operator and .Equals() method?

A

The == operator in C# is used to compare two objects for reference equality, meaning it checks whether the two objects are the same instance in memory.

On the other hand, the .Equals() method is used to compare the actual values of the two objects, based on how the method is implemented for a particular class.

For value types like int, bool, double, and structs, the == operator compares the values, whereas for reference types like string and custom classes, it compares the references.

It’s important to note that the behavior of the == operator can be overridden for reference types by overloading the operator, allowing it to compare values instead of references.

The .Equals() method can also be overridden in classes to provide custom equality comparisons.

By default, it behaves like the == operator for reference types but can be customized to compare values instead.

49
Q

What is the purpose of the var keyword in C#?

A

Introduced in C# 3.0 along with the Language-Integrated Query (LINQ) features, the var keyword primarily serves to reduce redundancy.

Key Benefits
Code Conciseness: It streamlines code by inferring types, especially with complex types or generic data structures.

Dynamic and Anonymous Types Support: It’s useful when using dynamic types or initializing objects with an anonymous type; a feature useful in LINQ queries.

Avoid Misusing var
It’s important to use var with caution to prevent these issues:

Type Clarity: Incorporating explicit type declarations can enhance code clarity, especially for beginners or when working with inherited code.

Code Readability for Method Chaining: Avoid using var excessively when chaining methods to maintain readability.

Best Practices and Common Use-Cases
Initialization: Use var while initializing; it helps adapt to object type changes, reduces redundancy, and aligns with the DRY (Don’t Repeat Yourself) principle.

For-Each Loops with Collections: It’s standard practice to use var in for-each loops when iterating through collections**.

Complex or Generic Types: var brings clarity and brevity when working with such types.

50
Q

What are the differences between const and readonly keywords?

A

C# supports two mechanisms for creating immutable fields: const and readonly.

Key Distinctions
Initialization: const fields are initialized when declared, while readonly fields can be initialized at the point of declaration or in the class constructor.

Visibility: readonly fields allow for differing values within different class instances, whereas const ensures the same value across all instances.

Type Compatibility: const fields are limited to primitive data types, String, and null. readonly can be utilized with any data type.

Compile-Time/Run-Time: **const fields are evaluated at compile time. On the contrary, readonly fields are evaluated at run-time, **fittingly appealing to scenarios that necessitate a run-time reference or state.

51
Q

How does checked and unchecked context affect arithmetic operations?

A

In C#, the enablers checked and unchecked ensure more predictable behavior when using specific arithmetic operations. By default, C# employs overflow checking, but you can toggle to overflow wrapping using appropriate blocks.

Context Control Keywords
-> checked: Forces operations to produce exceptions for overflow.
-> unchecked: Causes operations to wrap on overflow.

When to Use Each Context
-> checked: Ideal when you require accurate numeric results to guarantee that potential overflows are detected and handled.

->unchecked: Primarily used to enhance performance in scenarios where the logic or the expected input range ensures that overflows are less probable or inconsequential.

52
Q

What are the different ways to handle errors in C#?

A

C# offers multiple mechanisms for handling errors, from traditional exception handling to contemporary asynchronous error management strategies.

5 Key Methods for Error Handling in C#

  1. Exception Handling: Based on try-catch, primarily for synchronous flows but also compatible with some asynchronous scenarios. Exceptions are caught and processed within catch blocks.
  2. Logging and Monitoring: Involves using services like ILogger or specialized tools to capture, evaluate, and report application errors.
  3. HTTP Status Codes: Typically utilized in web applications to convey the status of a web request. RESTful services also often use these codes for error management.
  4. Return Values: Methods and functions can provide customized return values to signify different error states.
  5. Task<T> and Task: Primarily for asynchronous programming, indicating error states through Task results (.Result) or Task<T> members (.IsFaulted).</T></T>
53
Q

Explain the role of the garbage collector in .NET.

A

The Garbage Collector (GC) is a key feature in .NET that automates memory management. Rather than requiring manual memory deallocation (as seen in languages like C/C++), the GC identifies and recovers memory that’s no longer in use.

Benefits of Automatic Memory Management
Reduced Memory Leaks: The GC helps prevent leaks by reclaiming memory that’s no longer accessible, even if the programmer forgets to free it.

Simplified Memory Management: Developers are freed from tedious tasks like memory allocation, tracking object lifetimes, and memory deallocation.

Protection from Use-after-Free Bugs: Segmentation faults and other issues caused by accessing memory that’s been freed are avoided.

54
Q

Fundamentals of the Garbage Collector

A

Trigger Mechanism: The GC is triggered in the background whenever certain memory thresholds are reached, reducing interruption to your program’s execution.

Process Overview: It divides memory into three generations, each associated with a different cleanup frequency. Most objects are initially allocated in the first generation (Gen0). When the GC cleans up Gen0, it may promote some objects to Gen1, and so forth. The idea is that, over time, surviving objects are promoted to higher generations and require less frequent cleanup.

Mark and Sweep: During the cleanup cycle, the GC marks all reachable objects and then reclaims the memory occupied by objects that weren’t marked. This process ensures that only inaccessible objects are collected.

55
Q

Recommendations for Handling Memory in .NET in GC

A

Limit High-Frequency Object Instantiation: Frequent creation and destruction of small, short-lived objects can lead to inefficient GC usage. Consider using object pools for such scenarios.

Dispose of Unmanaged Resources: Certain resources, like file handles or database connections, may not be managed by the GC alone. It’s crucial to release them explicitly, typically by implementing the IDisposable pattern.

Consider Generational Behavior: The GC’s generational approach means that data-heavy long-lived objects (LLDs) could remain in memory for extended periods. Be mindful of LLDs’ persistence and their impact on memory consumption.