Topics List
C# Fundamentals
- What are the differences between
const
andreadonly
? - What are the differences between
ref
andout
? - Explain value types and reference types.
- What are stack and heap?
- What is the difference between
checked
andunchecked
? - What are
fixed
andunsafe
keywords? - What is the use of the
using
keyword? - What is the
new
keyword?
Memory Management and Resources
- What is garbage collection, and how does it work? What are generations?
- What is the DLL Hell problem, and how is it solved?
- How to use Win32 API in C#?
- What are managed and unmanaged code?
- How to identify an unmanaged resource?
- How to deal with an unmanaged resource? Explain with an example.
Advanced C# Features
- What are indexers?
- What are extension methods?
- What are collections?
- What collections are available in .NET?
- What are the advantages of using collections over generics?
- What are generic collections?
- What are generics in .NET, and what are its constraints?
Version-Specific Topics
C# 1.0
- Introduction to C# and its core syntax
- Basic types, control structures, and loops
- Classes, interfaces, and inheritance
C# 2.0
- What are partial classes?
- What are nullable types?
- What are iterators and
yield
? - What are anonymous methods?
C# 3.0
- What are lambda expressions?
- What is LINQ?
- What are expression trees?
- What are anonymous types?
- What is the
var
keyword?
C# 4.0
- What are dynamic types?
- What are named and optional parameters?
- What is covariance and contravariance?
C# 5.0
- What is asynchronous programming (
async
andawait
)? - What are caller info attributes?
- What is asynchronous programming (
C# 6.0
- What is null-conditional operator (
?.
)? - What are expression-bodied members?
- What is string interpolation?
- What is null-conditional operator (
C# 7.0
- What are tuples and deconstruction?
- What are pattern matching enhancements?
- What are local functions?
C# 8.0
- What are nullable reference types?
- What are asynchronous streams?
- What are indices and ranges?
- What are default interface methods?
C# 9.0
- What are record types?
- What are init-only setters?
- What are top-level statements?
C# 10.0
- What are global using directives?
- What is file-scoped namespace declaration?
- What are record structs?
Now let's explore each topic in detail with explanations and examples.
C# Fundamentals
1. What are the differences between const
and readonly
?
const
:- Represents compile-time constants.
- Must be initialized at the time of declaration.
- Implicitly static and cannot be modified.
- Example:csharp
const int MaxValue = 100;
readonly
:- Represents runtime constants.
- Can be initialized either at the time of declaration or in a constructor.
- Can be instance-level or static.
- Example:csharp
public class Example { public readonly int InstanceValue; public static readonly int StaticValue; public Example(int value) { InstanceValue = value; } }
2. What are the differences between ref
and out
?
ref
:- Requires that the variable is initialized before being passed to a method.
- Allows a method to read and modify the argument.
- Example:csharp
void ModifyRef(ref int x) { x += 10; } int number = 5; ModifyRef(ref number); // number is now 15
out
:- Does not require initialization before being passed.
- Must be assigned a value within the method before it returns.
- Example:csharp
void GetValues(out int a, out int b) { a = 5; b = 10; } int x, y; GetValues(out x, out y); // x is 5, y is 10
3. Explain value types and reference types.
Value Types:
- Store data directly in their memory allocation.
- Include primitive types (e.g.,
int
,float
,bool
) and structures. - Stored in the stack.
- Example:csharp
int x = 10;
Reference Types:
- Store a reference to the data's memory location.
- Include classes, interfaces, arrays, and delegates.
- Stored in the heap, but the reference is stored in the stack.
- Example:csharp
class Person { public string Name { get; set; } } Person person = new Person();
4. What are stack and heap?
Stack:
- Used for static memory allocation.
- Stores value types and the reference part of reference types.
- Follows a Last In, First Out (LIFO) principle.
- Fast access and automatic memory management.
Heap:
- Used for dynamic memory allocation.
- Stores objects and data referenced by reference types.
- Managed by the garbage collector for memory allocation and deallocation.
- Slower access compared to the stack due to dynamic allocation.
5. What is the difference between checked
and unchecked
?
checked
:- Ensures that arithmetic operations and conversions are checked for overflow.
- Throws an
OverflowException
if overflow occurs. - Example:csharp
int result = checked(2147483647 + 1); // Throws OverflowException
unchecked
:- Ignores overflow during arithmetic operations and conversions.
- Default behavior in C# unless explicitly specified.
- Example:csharp
int result = unchecked(2147483647 + 1); // Overflow occurs, but no exception
6. What are fixed
and unsafe
keywords?
fixed
:- Pins an object in memory, preventing the garbage collector from moving it.
- Used in unsafe code to work with pointers.
- Example:csharp
unsafe { int[] numbers = { 1, 2, 3 }; fixed (int* p = numbers) { // p is a pointer to the array } }
unsafe
:- Allows the use of pointers and direct memory manipulation.
- Requires the
/unsafe
compiler option. - Example:csharp
unsafe { int number = 5; int* p = &number; Console.WriteLine(*p); // Outputs 5 }
7. What is the use of the using
keyword?
using
:- Manages resource disposal for objects that implement
IDisposable
. - Automatically calls
Dispose
method at the end of the block. - Also used to import namespaces.
- Example:csharp
using (var stream = new FileStream("file.txt", FileMode.Open)) { // Use the stream } // stream.Dispose() is called here
- Manages resource disposal for objects that implement
8. What is the new
keyword?
new
:Instantiates a new object.
Hides a member inherited from a base class (shadowing).
Example (instantiation):
csharpPerson person = new Person();
Example (shadowing):
csharpclass BaseClass { public void Display() => Console.WriteLine("Base Class"); } class DerivedClass : BaseClass { public new void Display() => Console.WriteLine("Derived Class"); }
Memory Management and Resources
9. What is garbage collection, and how does it work? What are generations?
Garbage Collection:
- Automatically manages memory allocation and deallocation.
- Reclaims memory occupied by objects that are no longer in use.
- Uses a mark-and-sweep algorithm to identify and remove unreachable objects.
Generations:
- Optimize garbage collection by categorizing objects by their lifespan.
- Generation 0: Short-lived objects (e.g., temporary variables).
- Generation 1: Medium-lived objects.
- Generation 2: Long-lived objects (e.g., static data, global variables).
Example:
csharpclass Program { static void Main() { for (int i = 0; i < 1000; i++) { var obj = new object(); // Short-lived objects in Gen 0 } GC.Collect(); // Force garbage collection } }
10. What is the DLL Hell problem, and how is it solved?
DLL Hell:
- A problem caused by version conflicts and dependency issues with shared DLLs.
- Occurs when applications overwrite DLLs with incompatible versions, leading to runtime errors.
Solution:
- Strong Naming: Assigns a unique version and public key to each assembly, allowing multiple versions to coexist.
- Global Assembly Cache (GAC): Stores shared assemblies and resolves conflicts based on version.
- Side-by-Side Execution: Allows multiple versions of the same assembly to run simultaneously.
11. How to use Win32 API in C#?
P/Invoke (Platform Invocation Services):
- Allows calling native functions from unmanaged DLLs.
- Requires
DllImport
attribute to specify the DLL and function signature.
Example:
csharpusing System; using System.Runtime.InteropServices; class Program { [DllImport("user32.dll")] public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type); static void Main() { MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0); } }
12. What are managed and unmanaged code?
Managed Code:
- Executed by the .NET runtime (CLR).
- Provides services like garbage collection, type safety, and exception handling.
Unmanaged Code:
- Executed directly by the operating system.
- Lacks runtime services and requires explicit memory management (e.g., C/C++ code).
13. How to identify an unmanaged resource?
- Unmanaged Resources:
- Not handled by the .NET garbage collector.
- Include file handles, database connections, network sockets, etc.
- Require explicit release using
IDisposable
or finalizers.
14. How to deal with an unmanaged resource? Explain with an example.
Managing Unmanaged Resources:
- Implement
IDisposable
to provide aDispose
method for cleanup. - Use
SafeHandle
for better resource management.
- Implement
Example:
csharpusing System; using System.Runtime.InteropServices; class UnmanagedResource : IDisposable { private IntPtr resourceHandle; public UnmanagedResource() { // Allocate unmanaged resource resourceHandle = Marshal.AllocHGlobal(100); } public void Dispose() { // Release unmanaged resource Marshal.FreeHGlobal(resourceHandle); } } class Program { static void Main() { using (var resource = new UnmanagedResource()) { // Use the resource } // resource.Dispose() is called here } }
Advanced C# Features
15. What are indexers?
- Indexers:
- Allow instances of a class or struct to be indexed like arrays.
- Defined using the
this
keyword with a parameter list. - Example:csharp
class SampleCollection<T> { private T[] array = new T[100]; public T this[int index] { get => array[index]; set => array[index] = value; } } class Program { static void Main() { var collection = new SampleCollection<int>(); collection[0] = 10; Console.WriteLine(collection[0]); // Outputs 10 } }
16. What are extension methods?
- Extension Methods:
- Allow adding new methods to existing types without modifying them.
- Defined as static methods in a static class, with the
this
keyword before the first parameter. - Example:csharp
public static class StringExtensions { public static int WordCount(this string str) { return str.Split(new[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; } } class Program { static void Main() { string text = "Hello, world!"; int count = text.WordCount(); // Invokes the extension method Console.WriteLine(count); // Outputs 2 } }
17. What are collections?
- Collections:
- Store and manage groups of related objects.
- Provide dynamic sizing and advanced data manipulation.
- Include various types, such as lists, dictionaries, and queues.
18. What collections are available in .NET?
- Common Collections:
- List<T>: Dynamic array implementation.
- Dictionary<TKey, TValue>: Key-value pair storage.
- Queue<T>: First In, First Out (FIFO) collection.
- Stack<T>: Last In, First Out (LIFO) collection.
- HashSet<T>: Unordered collection of unique elements.
19. What are the advantages of using collections over generics?
- Advantages:
- Collections provide pre-built data structures and algorithms for managing groups of objects.
- Generics allow for type safety, avoiding boxing and unboxing, and improving performance.
- Collections often use generics internally, combining the benefits of both.
20. What are generic collections?
- Generic Collections:
- Allow storage of elements of a specified type, ensuring type safety.
- Reduce the need for type casting and improve performance.
- Example:csharp
List<int> numbers = new List<int> { 1, 2, 3 }; numbers.Add(4);
21. What are generics in .NET, and what are its constraints?
Generics:
- Allow the definition of classes, interfaces, and methods with a placeholder for the data type.
- Provide type safety and reduce code duplication.
Constraints:
- Limit the types that can be used as arguments for type parameters.
- Common constraints include:
where T : struct
: T must be a value type.where T : class
: T must be a reference type.where T : new()
: T must have a parameterless constructor.where T : SomeBaseClass
: T must inherit fromSomeBaseClass
.where T : ISomeInterface
: T must implementISomeInterface
.
Example:
csharpclass GenericClass<T> where T : new() { public T CreateInstance() { return new T(); } }
Version-Specific Topics
C# 1.0
Introduction to C# and its core syntax:
- Basic syntax includes variables, data types, operators, and control structures.
- Example:csharp
int number = 5; if (number > 0) { Console.WriteLine("Positive"); }
Basic types, control structures, and loops:
- Basic types include
int
,float
,bool
,char
, andstring
. - Control structures:
if
,else
,switch
,while
,do-while
,for
, andforeach
.
- Basic types include
Classes, interfaces, and inheritance:
- Classes define objects and encapsulate data and behavior.
- Interfaces define contracts for classes to implement.
- Inheritance allows classes to derive from other classes.
- Example:csharp
class Animal { public virtual void Speak() => Console.WriteLine("Animal sound"); } class Dog : Animal { public override void Speak() => Console.WriteLine("Bark"); }
C# 2.0
What are partial classes?
- Allow splitting a class definition across multiple files.
- Useful for organizing large classes and working in teams.
- Example:csharp
// File1.cs partial class MyClass { public void Method1() => Console.WriteLine("Method1"); } // File2.cs partial class MyClass { public void Method2() => Console.WriteLine("Method2"); }
What are nullable types?
- Allow value types to represent null values using
Nullable<T>
orT?
. - Useful for database operations and optional fields.
- Example:csharp
int? nullableInt = null; if (nullableInt.HasValue) { Console.WriteLine(nullableInt.Value); }
- Allow value types to represent null values using
What are iterators and
yield
?- Simplify the implementation of custom iterators using
yield return
. - Provide a way to iterate over collections without exposing the underlying data structure.
- Example:csharp
class Numbers { public System.Collections.IEnumerable GetNumbers() { yield return 1; yield return 2; yield return 3; } } class Program { static void Main() { var numbers = new Numbers(); foreach (var number in numbers.GetNumbers()) { Console.WriteLine(number); } } }
- Simplify the implementation of custom iterators using
What are anonymous methods?
- Define inline unnamed methods using the
delegate
keyword. - Useful for event handling and short-lived methods.
- Example:csharp
System.Action<int> printNumber = delegate (int number) { Console.WriteLine(number); }; printNumber(5);
- Define inline unnamed methods using the
C# 3.0
What are lambda expressions?
- Simplify anonymous methods using the
=>
syntax. - Provide a concise way to write functions and predicates.
- Example:csharp
System.Func<int, int> square = x => x * x; Console.WriteLine(square(5)); // Outputs 25
- Simplify anonymous methods using the
What is LINQ?
- Language Integrated Query for querying collections and databases.
- Provides a unified syntax for data manipulation.
- Example:csharp
int[] numbers = { 1, 2, 3, 4, 5 }; var evenNumbers = from n in numbers where n % 2 == 0 select n; foreach (var n in evenNumbers) { Console.WriteLine(n); // Outputs 2, 4 }
What are expression trees?
- Represent code as data structures, enabling dynamic code generation and execution.
- Useful for LINQ providers and dynamic query generation.
- Example:csharp
System.Linq.Expressions.Expression<System.Func<int, bool>> expr = num => num > 5; Console.WriteLine(expr.Body); // Outputs (num > 5)
What are anonymous types?
- Allow creating objects without explicitly defining a class.
- Useful for storing a set of read-only properties.
- Example:csharp
var person = new { Name = "John", Age = 30 }; Console.WriteLine(person.Name); // Outputs "John"
What is the
var
keyword?- Enables implicit typing, allowing the compiler to infer the variable type.
- Useful for reducing code verbosity.
- Example:csharp
var message = "Hello, World!"; Console.WriteLine(message);
C# 4.0
What are dynamic types?
- Allow bypassing compile-time type checking, resolving types at runtime.
- Useful for COM interoperability and dynamic languages.
- Example:csharp
dynamic obj = 10; Console.WriteLine(obj + 5); // Outputs 15
What are named and optional parameters?
- Allow specifying parameter names and providing default values.
- Improve code readability and flexibility.
- Example:csharp
void PrintMessage(string message, int repeat = 1) { for (int i = 0; i < repeat; i++) { Console.WriteLine(message); } } PrintMessage("Hello", repeat: 3); // Named parameter PrintMessage("Hi"); // Uses default value for repeat
What is covariance and contravariance?
- Allow more flexibility in assigning compatible types to generic interfaces and delegates.
- Covariance: Enables a derived type to be used in place of a base type.
- Contravariance: Enables a base type to be used in place of a derived type.
Example:
csharpSystem.Collections.Generic.IEnumerable<string> strings = new[] { "A", "B", "C" }; System.Collections.Generic.IEnumerable<object> objects = strings; // Covariance System.Action<object> actionObject = obj => Console.WriteLine(obj); System.Action<string> actionString = actionObject; // Contravariance
C# 5.0
What is asynchronous programming (
async
andawait
)?- Simplify writing asynchronous code using
async
andawait
keywords. - Improve application responsiveness by offloading long-running operations.
- Example:csharp
async System.Threading.Tasks.Task<int> GetDataAsync() { await System.Threading.Tasks.Task.Delay(1000); // Simulate delay return 42; } async System.Threading.Tasks.Task MainAsync() { int result = await GetDataAsync(); Console.WriteLine(result); // Outputs 42 }
- Simplify writing asynchronous code using
What are caller info attributes?
- Provide information about the caller of a method, such as file path, line number, and member name.
- Useful for logging and debugging.
- Example:csharp
void LogMessage(string message, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "") { Console.WriteLine($"{memberName}: {message}"); } void SomeMethod() { LogMessage("Hello, World!"); // Outputs "SomeMethod: Hello, World!" }
C# 6.0
What is null-conditional operator (
?.
)?- Simplify null checks by short-circuiting member access and method calls.
- Example:csharp
string text = null; int? length = text?.Length; // length is null
What are expression-bodied members?
- Simplify method, property, and operator definitions using
=>
. - Example:csharp
class Circle { public double Radius { get; set; } public double Area => System.Math.PI * Radius * Radius; }
- Simplify method, property, and operator definitions using
What is string interpolation?
- Simplify string formatting using
$
and{}
syntax. - Example:csharp
string name = "John"; int age = 30; string message = $"Name: {name}, Age: {age}"; Console.WriteLine(message);
- Simplify string formatting using
C# 7.0
What are tuples and deconstruction?
- Simplify grouping multiple values using tuples and extracting them using deconstruction.
- Example:csharp
(int, string) GetPerson() => (30, "John"); var (age, name) = GetPerson(); Console.WriteLine($"{name} is {age} years old.");
What are pattern matching enhancements?
- Simplify code by using patterns in
switch
statements and expressions. - Example:csharp
object obj = 42; switch (obj) { case int i: Console.WriteLine($"Integer: {i}"); break; case string s: Console.WriteLine($"String: {s}"); break; }
- Simplify code by using patterns in
What are local functions?
- Define functions within a method to encapsulate logic.
- Improve code organization and readability.
- Example:csharp
void ProcessData(int data) { void Display(int value) => Console.WriteLine(value); Display(data); }
C# 8.0
What are nullable reference types?
- Enable nullable annotations and warnings for reference types.
- Improve code safety by highlighting potential null reference issues.
- Example:csharp
string? nullableText = null; if (nullableText != null) { Console.WriteLine(nullableText.Length); }
What are asynchronous streams?
- Allow consuming streams of data asynchronously using
await foreach
. - Example:csharp
async System.Collections.Generic.IAsyncEnumerable<int> GetNumbersAsync() { for (int i = 0; i < 5; i++) { await System.Threading.Tasks.Task.Delay(1000); yield return i; } } async System.Threading.Tasks.Task MainAsync() { await foreach (var number in GetNumbersAsync()) { Console.WriteLine(number); } }
- Allow consuming streams of data asynchronously using
What are indices and ranges?
- Simplify accessing elements in arrays and collections using indices and ranges.
- Example:csharp
int[] numbers = { 0, 1, 2, 3, 4, 5 }; int last = numbers[^1]; // 5 int[] subArray = numbers[1..4]; // { 1, 2, 3 }
What are default interface methods?
- Allow providing default implementations in interfaces.
- Enable interface evolution without breaking existing implementations.
- Example:csharp
interface IShape { double Area { get; } double Perimeter => 0; // Default implementation } class Circle : IShape { public double Radius { get; set; } public double Area => System.Math.PI * Radius * Radius; }
C# 9.0
What are record types?
- Provide immutable reference types for modeling data.
- Simplify value-based equality and deconstruction.
- Example:csharp
record Person(string Name, int Age); var person = new Person("John", 30); Console.WriteLine(person);
What are init-only setters?
- Allow setting properties only during object initialization.
- Improve immutability and encapsulation.
- Example:csharp
class Point { public int X { get; init; } public int Y { get; init; } } var point = new Point { X = 10, Y = 20 };
What are pattern matching enhancements?
- Introduce new patterns and improve existing pattern matching capabilities.
- Example:csharp
object obj = (42, "Hello"); if (obj is (int number, string message)) { Console.WriteLine($"{message}: {number}"); }
What are top-level statements?
- Simplify writing simple programs without explicitly defining a
Main
method. - Example:csharp
System.Console.WriteLine("Hello, World!");
- Simplify writing simple programs without explicitly defining a
What is the
new
keyword in thewith
expression?- Simplify creating modified copies of immutable objects.
- Example:csharp
record Person(string Name, int Age); var person = new Person("John", 30); var newPerson = person with { Age = 31 };
What are native-sized integers (
nint
andnuint
)?- Provide platform-specific integer types for low-level programming.
- Example:csharp
nint nativeInt = 10; nuint nativeUInt = 20;
C# 10.0
What are global using directives?
- Simplify imports by specifying namespaces globally across a project.
- Example:csharp
// GlobalUsings.cs global using System; global using System.Collections.Generic;
What are file-scoped namespaces?
- Reduce indentation by declaring namespaces for an entire file.
- Example:csharp
namespace MyNamespace; class MyClass { // ... }
What are record structs?
- Provide value types with record-like syntax and semantics.
- Example:csharp
record struct Point(int X, int Y);
What are improvements to lambda expressions?
- Introduce new features and improvements to lambda expressions.
- Example:csharp
System.Func<int, int> square = (int x) => x * x;
C# 11.0
What are required properties?
- Enforce initialization of properties during object creation.
- Example:csharp
class Person { public required string Name { get; set; } public int Age { get; set; } } var person = new Person { Name = "John", Age = 30 };
What are generic attributes?
- Allow specifying generic parameters for attributes.
- Example:csharp
[SomeAttribute<int>] class MyClass { // ... }
What are raw string literals?
- Simplify writing multi-line and embedded string literals.
- Example:csharp
string json = """ { "name": "John", "age": 30 } """;
What are new pattern matching features?
- Introduce additional pattern matching features and enhancements.
- Example:csharp
int number = 5; if (number is > 0 and < 10) { Console.WriteLine("Between 0 and 10"); }
C# Libraries and Frameworks
ASP.NET Core
Overview and basic usage:
- Open-source, cross-platform framework for building web applications.
- Provides features for creating APIs, web apps, and microservices.
- Example:csharp
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello, World!"); app.Run();
Dependency injection:
- Built-in support for dependency injection.
- Encourages loose coupling and testability.
- Example:csharp
builder.Services.AddSingleton<IMyService, MyService>(); class MyService : IMyService { // ... }
Middleware:
- Pipeline components for handling HTTP requests and responses.
- Example:csharp
app.Use(async (context, next) => { Console.WriteLine("Request started"); await next(); Console.WriteLine("Request ended"); });
Entity Framework Core
Object-relational mapping (ORM) for .NET:
- Simplifies database access by mapping objects to database tables.
- Example:csharp
class MyDbContext : DbContext { public DbSet<Person> People { get; set; } } class Person { public int Id { get; set; } public string Name { get; set; } }
Code-first and database-first approaches:
- Code-first: Define models in code and generate database schema.
- Database-first: Generate models from existing database schema.
- Example (Code-first):csharp
var options = new DbContextOptionsBuilder<MyDbContext>() .UseSqlServer(connectionString) .Options; using var context = new MyDbContext(options); context.People.Add(new Person { Name = "John" }); context.SaveChanges();
Xamarin
Cross-platform mobile app development:
- Build native iOS and Android apps using C# and .NET.
- Example:csharp
public class App : Application { public App() { MainPage = new ContentPage { Content = new Label { Text = "Hello, Xamarin!" } }; } }
Shared codebase and native UI:
- Share code across platforms while accessing native APIs.
- Example:csharp
using Xamarin.Essentials; class MyPage : ContentPage { public MyPage() { var location = Geolocation.GetLastKnownLocationAsync().Result; } }
WPF (Windows Presentation Foundation)
Rich client application development:
- Build visually rich desktop applications using XAML and .NET.
- Example:xaml
<Window x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MyApp" Height="350" Width="525"> <Grid> <Button Content="Click Me" Click="Button_Click"/> </Grid> </Window>
Data binding and MVVM pattern:
- Bind UI elements to data sources for dynamic updates.
- MVVM (Model-View-ViewModel) pattern promotes separation of concerns.
- Example:csharp
public class MainViewModel : INotifyPropertyChanged { private string message; public string Message { get => message; set { message = value; OnPropertyChanged(nameof(Message)); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
Blazor
WebAssembly-based single-page applications (SPA):
- Build interactive web apps using C# and .NET.
- Example:csharp
@page "/counter" <h1>Counter</h1> <p>Current count: @currentCount</p> <button @onclick="IncrementCount">Increment</button> @code { private int currentCount = 0; private void IncrementCount() { currentCount++; } }
Server-side and client-side hosting models:
- Server-side: Executes components on the server and interacts with the client via SignalR.
- Client-side: Executes components directly in the browser using WebAssembly.
Certainly! Let's continue with more topics on C# programming and .NET, covering additional features, libraries, and frameworks across different versions.
Additional Topics in C# and .NET
C# 11.0 (continued)
What are list patterns?
- Enable pattern matching against elements in a list or array.
- Example:csharp
int[] numbers = { 1, 2, 3, 4 }; if (numbers is [1, 2, .. var rest]) { Console.WriteLine($"Starts with 1, 2. Remaining: {string.Join(", ", rest)}"); }
What are interpolated string handlers?
- Provide custom logic for handling interpolated strings, enhancing performance and flexibility.
- Example:csharp
class CustomHandler { public CustomHandler(int literalLength, int formattedCount) { // Initialization logic } public void AppendLiteral(string s) { // Handle literal parts } public void AppendFormatted<T>(T t) { // Handle formatted parts } } [InterpolatedStringHandler] public static void LogMessage(CustomHandler handler) { // Custom logging logic } LogMessage($"Processing data at {DateTime.Now}");
What are static abstract members in interfaces?
- Define static abstract methods in interfaces, allowing static polymorphism.
- Example:csharp
interface IOperations<T> { static abstract T Add(T a, T b); } struct IntegerOperations : IOperations<int> { public static int Add(int a, int b) => a + b; }
C# Libraries and Frameworks (continued)
.NET MAUI (Multi-platform App UI)
Overview and basic usage:
- Evolution of Xamarin.Forms for building cross-platform apps.
- Supports Android, iOS, Windows, and macOS.
- Example:csharp
public class App : Application { public App() { MainPage = new MainPage(); } } public class MainPage : ContentPage { public MainPage() { Content = new Label { Text = "Welcome to .NET MAUI!", VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand, }; } }
Cross-platform UI and logic:
- Share UI and business logic across multiple platforms.
- Example:csharp
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyApp.MainPage"> <StackLayout> <Label Text="Welcome to .NET MAUI!" VerticalOptions="Center" HorizontalOptions="Center" /> <Button Text="Click Me" Clicked="OnButtonClick"/> </StackLayout> </ContentPage>
Azure Functions
Serverless computing with .NET:
- Build and deploy event-driven, scalable applications using Azure Functions.
- Example:csharp
public static class Function1 { [FunctionName("Function1")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["name"]; return new OkObjectResult($"Hello, {name}"); } }
Integrating with other Azure services:
- Use Azure Functions to respond to events from Azure Blob Storage, Service Bus, and more.
- Example:csharp
public static class BlobTriggeredFunction { [FunctionName("BlobTriggeredFunction")] public static void Run( [BlobTrigger("samples-workitems/{name}", Connection = "AzureWebJobsStorage")] Stream myBlob, string name, ILogger log) { log.LogInformation($"Blob trigger function processed blob\n Name: {name}"); } }
SignalR
Real-time web applications:
- Build applications with real-time communication between server and client.
- Example:csharp
public class ChatHub : Microsoft.AspNetCore.SignalR.Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } // Client-side JavaScript const connection = new signalR.HubConnectionBuilder() .withUrl("/chatHub") .build(); connection.on("ReceiveMessage", (user, message) => { console.log(`${user}: ${message}`); }); connection.start().catch(err => console.error(err));
Handling connections and groups:
- Manage connections and group users for targeted messaging.
- Example:csharp
public class NotificationHub : Hub { public async Task AddToGroup(string groupName) { await Groups.AddToGroupAsync(Context.ConnectionId, groupName); } public async Task SendMessageToGroup(string groupName, string message) { await Clients.Group(groupName).SendAsync("ReceiveMessage", message); } }
gRPC with .NET
High-performance RPC framework:
- Build efficient, cross-platform services with gRPC using .NET.
- Example:proto
syntax = "proto3"; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }
Server and client implementation:
- Define services and use gRPC tools to generate server and client code.
- Example (Server):csharp
public class GreeterService : Greeter.GreeterBase { public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) { return Task.FromResult(new HelloReply { Message = $"Hello, {request.Name}" }); } }
Streaming and bidirectional communication:
- Support for streaming data between server and client.
- Example (Client-side streaming):csharp
public async Task SendGreetingsAsync(Greeter.GreeterClient client) { using var call = client.SayHelloStream(); for (int i = 0; i < 5; i++) { await call.RequestStream.WriteAsync(new HelloRequest { Name = $"User {i}" }); } await call.RequestStream.CompleteAsync(); var response = await call; Console.WriteLine(response.Message); }
Azure SDK for .NET
Azure service integration:
- Utilize Azure SDKs to interact with Azure services, such as storage, databases, and cognitive services.
- Example:csharp
var blobServiceClient = new BlobServiceClient(connectionString); var containerClient = blobServiceClient.GetBlobContainerClient("my-container"); var blobClient = containerClient.GetBlobClient("my-blob.txt"); await blobClient.UploadAsync(new BinaryData("Hello, Azure!"));
Authentication and authorization:
- Use Azure Identity libraries for secure authentication.
- Example:csharp
var credential = new DefaultAzureCredential(); var secretClient = new SecretClient(new Uri("https://my-vault.vault.azure.net/"), credential); var secret = await secretClient.GetSecretAsync("MySecret"); Console.WriteLine(secret.Value);
.NET Core CLI and Tooling
Building and managing projects:
- Use the .NET CLI to create, build, run, and manage projects.
- Example:shell
dotnet new console -n MyConsoleApp dotnet build dotnet run
Package management with NuGet:
- Install and manage dependencies using NuGet packages.
- Example:shell
dotnet add package Newtonsoft.Json dotnet restore
Global tools:
- Install and use global tools for enhanced development productivity.
- Example:shell
dotnet tool install --global dotnet-ef dotnet ef migrations add InitialCreate
Roslyn Compiler and C# Scripting
Analyzers and code generation:
- Use Roslyn to write code analyzers and generate code dynamically.
- Example:csharp
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; var tree = CSharpSyntaxTree.ParseText(@"class C { void M() { } }"); var root = tree.GetRoot() as CompilationUnitSyntax; Console.WriteLine(root.DescendantNodes().OfType<MethodDeclarationSyntax>().Count()); // Outputs 1
C# interactive and scripting:
- Execute C# code interactively using C# scripting.
- Example:csharp
// C# Interactive > var message = "Hello, World!"; > Console.WriteLine(message);
Microservices and Containerization
Building microservices with .NET:
- Create scalable microservices using ASP.NET Core and Docker.
- Example:dockerfile
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base WORKDIR /app EXPOSE 80 FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["MyApp/MyApp.csproj", "MyApp/"] RUN dotnet restore "MyApp/MyApp.csproj" COPY . . WORKDIR "/src/MyApp" RUN dotnet build "MyApp.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "MyApp.dll"]
Service discovery and communication:
- Use tools like Consul or Dapr for service discovery and inter-service communication.
- Example (Dapr):shell
dapr run --app-id myapp --app-port 5000 --dapr-http-port 3500 dotnet run
.NET 6 and 7 Features
Minimal APIs:
- Build lightweight APIs with minimal configuration.
- Example:csharp
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello, World!"); app.Run();
Hot reload:
- Modify code while the app is running and see changes immediately.
- Example:shell
dotnet watch run
Source generators:
- Generate source code at compile time to reduce boilerplate.
- Example:csharp
[Generator] public class HelloWorldGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { context.AddSource("HelloWorld", SourceText.From(@" namespace HelloWorldGenerated { public static class HelloWorld { public static void SayHello() => System.Console.WriteLine(""Hello, World!""); } }", Encoding.UTF8)); } }