aspnetcore
ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
- 39k
- C#
- MIT
- 6 h ago
C# Basics
Repo learning-zone/csharp-basics, read from GitHub 23 h ago. learning-zone has not joined Take My Repo.
learning-zone/csharp-basics is a public repo on GitHub by learning-zone. C# Basics. It declares the MIT license on GitHub. It has 8 stars and last changed on 2026-08-09. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-21.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Click ★ if you like the project. Your contributions are heartily ♡ welcome.
Focus: Syntax, basic language constructs, and core type system.
C# syntax.Focus: Object-oriented programming, collections, and common language features.
Focus: Concurrency, memory management, and advanced language features.
Focus: Architecture, scalability, performance, and deployment strategies.
Span<T>, Memory<T>, object pooling, benchmarking, and profiling.C# patterns.C# (C-Sharp) is a modern, object-oriented, and type-safe programming language developed by Microsoft. It runs on the .NET platform and is designed to build a wide variety of secure and robust applications, including web apps, desktop software, mobile apps, cloud services, and video games.
Main features of C#:
1. Object-Oriented Programming (OOP)
C# fully supports core OOP pillars:
2. Type Safety and Static Typing
C# enforces strict type checking at compile-time:
3. Automatic Memory Management
Developers do not need to manually allocate and free up memory:
4. Type Inference (var)
While strongly typed, C# offers a var keyword:
5. Language Integrated Query (LINQ)
LINQ is a powerful, built-in feature that lets you query data inside C# code:
var adults = users.Where(u => u.Age >= 18);6. Asynchronous Programming (async / await)
C# makes writing non-blocking code remarkably simple:
7. Modern Language Enhancements
Microsoft updates C# annually with modern functional features:
C# is a strongly-typed language, meaning every variable and constant must have a declared data type. C# offers a variety of data types categorized as value types, reference types, and pointer types. Value types store data directly, while reference types store memory addresses to the actual data.
1. Value Types (Stored on the Stack)
Value types hold the actual data directly within their own memory space.
Integer Types
int: 32-bit signed integer (most common for whole numbers).long: 64-bit signed integer (for very large whole numbers).short: 16-bit signed integer.byte: 8-bit unsigned integer.Note: Unsigned variants exist, prefixed with 'u' (e.g., uint, ulong).
Floating-Point Types
float: 32-bit single-precision (requires f suffix, e.g., 3.14f).double: 64-bit double-precision (default for decimals).decimal: 128-bit high-precision (requires m suffix, e.g., 19.99m). Highly recommended for financial calculations.Other Simple Types
bool: Stores Boolean values (true or false).char: Stores a single 16-bit Unicode character (uses single quotes, e.g., 'A').Complex Value Types
struct: User-defined structures used to encapsulate small groups of related variables.enum: A distinct type that consists of a set of named constants.2. Reference Types:
Reference types do not store the actual data. Instead, they store a reference (a pointer) to the memory address where the data is kept.
string: Represents a sequence of Unicode characters (uses double quotes, e.g., "Hello").object: The ultimate base type from which all other types inherit.class: User-defined blueprints used to create objects.interface: Contracts that define a set of operations that a class or struct must implement.delegate: References to methods (used for events and callbacks).array: Collections of data elements of the same type (e.g., int[]).3. Pointer Types:
Used in unsafe code for direct memory manipulation (e.g., int*, char*).
4. Nullable Types:
Allow value types to represent null (e.g., int?, bool?).
Example:
using System;
class Program
{
static void Main()
{
// Value types
int age = 25;
double salary = 45000.75;
bool isActive = true;
char grade = 'A';
// Reference types
string name = "Pradeep";
int[] marks = { 80, 90, 85 };
object data = "Hello";
// Nullable type
int? optionalNumber = null;
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Salary: {salary}");
Console.WriteLine($"Is Active: {isActive}");
Console.WriteLine($"Grade: {grade}");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"First Mark: {marks[0]}");
Console.WriteLine($"Object Data: {data}");
Console.WriteLine($"Optional Number: {optionalNumber}");
}
}
Yes, primitive data types in C# (such as int, float, bool, etc.) are value types and are typically stored on the stack when used as local variables. However, they can be stored on the heap in certain scenarios:
1. Fields inside a Class
Classes are reference types and always live on the heap. Any primitive fields inside that class live on the heap with it.
public class Player
{
public int health = 100; // Stored on the heap inside the Player object
}
2. Boxing
Boxing converts a value type to a reference type. This copies the primitive value into a wrapper object on the heap
int age = 25; // Stored on the stack
object boxedAge = age; // The value 25 is copied to the heap
3. Elements in an Array
Arrays are reference types and live on the heap. Even if the array holds primitives, the data resides on the heap
int[] scores = new int[3]; // The three integers are stored on the heap
4. Variables in Closures (Lambda Expressions)
If a local primitive is used inside a lambda expression or LINQ query, the compiler moves it to a hidden class on the heap.
int multiplier = 2;
Func<int, int> myFunc = x => x * multiplier; // multiplier is moved to the heap
5. Async Method Variables
Local variables inside an async method that persist across an await point are stored in a state machine structure on the heap.
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
await CalculateAsync();
}
static async Task CalculateAsync()
{
int number = 10; // Local variable
Console.WriteLine($"Before await: {number}");
await Task.Delay(500); // Method is suspended here
// 'number' persists across the await point
number += 5;
Console.WriteLine($"After await: {number}");
}
}
Yes, it is possible to store mixed types, but not single strongly-type variable. However, there are several ways to achieve this depending on use case.
1. The object[] Array (Most Common)
In C#, every data type inherits from the base class object. Creating an array of objects allows you to store any data type inside it
// Implicit conversion happens automatically via "boxing"
object[] mixedArray = new object[] { 42, "Hello", 3.14f, 'A' };
// Accessing elements requires manual casting (unboxing)
int firstElement = (int)mixedArray[0];
string secondElement = (string)mixedArray[1];
2. The ArrayList Collection (Legacy)
Before C# introduced generics, ArrayList was the standard way to make a dynamically sizing mixed array. It functions identically to an object[] array under the hood.
using System.Collections;
ArrayList mixedList = new ArrayList();
mixedList.Add(42);
mixedList.Add("Hello");
mixedList.Add(3.14f);
mixedList.Add('A');
object[]3. Tuples (Best for Fixed-Size Records)
If you know exactly how many items you have and their position ahead of time, a Tuple provides a strongly-typed collection of mixed data without losing performance.
// Declaring a strongly-typed mixed group
var mixedTuple = (Number: 42, Text: "Hello", Decimal: 3.14f, Character: 'A');
// Accessing items is lightning fast and type-safe
int myInt = mixedTuple.Number;
string myString = mixedTuple.Text;
[i]).4. Custom Classes or Structs (Best for Data Models)
If your mixed array represents a specific entity (like a user profile containing an ID, Name, and Rating), wrapping the types inside a class or struct is the best practice.
public struct MixedData
{
public int MyInt;
public string MyString;
public float MyFloat;
public char MyChar;
}
// You can now safely make an array of this unified custom type
MixedData[] array = new MixedData[5];
An extension method in C# is a special kind of static method that allows you to add new functionality to an existing type (such as a class, interface, struct, or enum) without modifying its original source code, recompiling it, or using inheritance.
It is defined as a static method in a static class, with the first parameter prefixed with this. C# 14 also introduces extension members (a superset of extension methods).
1. Traditional extension method (all versions):
public static class StringExtensions
{
public static string Reverse(this string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
public static bool IsNullOrEmpty(this string? input)
=> string.IsNullOrEmpty(input);
}
// Usage
string text = "Hello";
Console.WriteLine(text.Reverse()); // Output: olleH
Console.WriteLine("".IsNullOrEmpty()); // Output: True
2. Extension methods with generic constraints (C# 11+):
public static class NumberExtensions
{
public static T Clamp<T>(this T value, T min, T max)
where T : System.Numerics.INumber<T>
=> T.Max(min, T.Min(value, max));
}
Console.WriteLine(15.Clamp(0, 10)); // Output: 10
Console.WriteLine(5.5.Clamp(0.0, 10.0)); // Output: 5.5
3. Extension members (C# 14 — new syntax):
C# 14 introduces a new extension block syntax that allows properties, static methods, and operators as extensions — not just instance methods:
extension(string s) StringEx
{
public int WordCount => s.Split(' ').Length;
public static string Repeat(string text, int times) => string.Concat(Enumerable.Repeat(text, times));
}
string sentence = "Hello World";
Console.WriteLine(sentence.WordCount); // Output: 2 (extension property)
Console.WriteLine(StringEx.Repeat("ha", 3)); // Output: hahaha
Note: Extension methods are resolved at compile time. They are found only when the namespace of the static class is imported with using.
In C#, a generic type is a blueprint that allows you to define classes, interfaces, structures, methods, or delegates with a placeholder (type parameter) instead of a specific data type. You specify the actual data type later, when you instantiate the class or call the method in your code. With C# 11 Generic Math, generic code can now also perform arithmetic operations across numeric types.
Features:
1. Generic class:
public class Repository<T>
{
private readonly List<T> _items = new();
public void Add(T item) => _items.Add(item);
public IReadOnlyList<T> GetAll() => _items;
}
var repo = new Repository<string>();
repo.Add("Pradeep");
repo.Add("Kumar");
Console.WriteLine(repo.GetAll().Count); // Output: 2
2. Generic method:
T Max<T>(T a, T b) where T : IComparable<T>
=> a.CompareTo(b) >= 0 ? a : b;
Console.WriteLine(Max(10, 20)); // Output: 20
Console.WriteLine(Max("apple", "mango")); // Output: mango
3. Generic Math (C# 11+, .NET 7+):
Write arithmetic algorithms that work over all numeric types using interfaces like INumber<T>, IAdditionOperators<T,T,T>, etc.
using System.Numerics;
T Sum<T>(IEnumerable<T> values) where T : INumber<T>
=> values.Aggregate(T.Zero, (acc, v) => acc + v);
Console.WriteLine(Sum(new[] { 1, 2, 3, 4 })); // Output: 10
Console.WriteLine(Sum(new[] { 1.5, 2.5, 3.0 })); // Output: 7
Console.WriteLine(Sum(new[] { 1m, 2m, 3.5m })); // Output: 6.5
4. Generic constraints:
| Constraint | Meaning |
|---|---|
where T : class |
T must be a reference type |
where T : struct |
T must be a value type |
where T : new() |
T must have a public parameterless constructor |
where T : IDisposable |
T must implement IDisposable |
where T : INumber<T> |
T must be a numeric type (C# 11+) |
where T : notnull |
T cannot be a nullable type (C# 8+) |
An anonymous method is a named method without a name, defined using the delegate keyword. It's used for inline code, particularly when you need to create a delegate instance without explicitly defining a named method first.
Anonymous methods are helpful when you need a small, one-time-use method and don't want to clutter the code with a separate named method.
Example:
using System;
class Program
{
// Define a delegate type
public delegate void PrintMessage(string message);
static void Main()
{
// Declaring an Anonymous Method
PrintMessage print = delegate(string val)
{
Console.WriteLine($"Anonymous Method Output: {val}");
};
// Invoking the delegate
print("Hello World!");
// Example with an Event Handler
// button.Click += delegate (object sender, EventArgs e) { LogClick(); };
}
}
Usage:
Note:
Lambda expressions are a more concise way to achieve the same functionality as anonymous methods. Lambda expressions are generally preferred over anonymous methods in modern C# code.
In C#, a function is always part of a class, making it a method. A function is a reusable block of code that can be called to perform a specific task. A method, in object-oriented programming, is associated with an object or class, often operating on the object's data or state.
Method: A block of code that belongs to a class or object and performs a specific action. It can access and modify the state (fields/properties) of the class.
Function: A general term for a block of code that performs a task and returns a value. In C#, standalone functions (not part of a class) do not exist; all functions are methods.
Example:
public class Calculator
{
// This is a method
public int Add(int a, int b)
{
return a + b;
}
}
The Common Language Runtime (CLR) — known as CoreCLR in modern .NET (formerly .NET Core) — is the core execution engine for .NET applications. It manages execution, memory, security, and cross-language interoperability. As of .NET 10, CoreCLR is cross-platform (Windows, Linux, macOS, Android, iOS, WebAssembly).
Key Functions:
Execution and Management: Manages the full lifecycle of .NET applications, including startup, execution, and shutdown.
Memory Management (Garbage Collection): Automatic, generational GC with server GC for high-throughput services and workstation GC for desktop apps. .NET 8/9/10 introduce further GC improvements such as the non-GC heap (pinned allocations exempt from GC pressure).
Just-In-Time (JIT) Compilation: Converts IL to native machine code at runtime using Tiered Compilation and Dynamic PGO (Profile-Guided Optimization). Alternatively, Native AOT compiles entirely at build time.
Security: Code Access Security was removed in .NET Core. Modern .NET relies on OS-level security, sandboxing, and runtime verification of IL.
Exception Handling: Structured exception handling with try/catch/finally, including AggregateException for parallel/async errors.
Cross-Language Interoperability: All .NET languages (C#, F#, VB.NET) share the Common Type System (CTS) and compile to IL, enabling seamless interop.
Metadata: Type information embedded in assemblies enables reflection, serialization, and source generators.
Core Architecture & Execution Flow
[ C# Source Code ]
│
▼ (Language Compiler: csc)
[ Common Intermediate Language (CIL) / Assembly ]
│
▼ (Loaded into the CLR Engine)
┌────────────────────────────────────────┐
│ Common Language Runtime (CLR) │
│ ┌──────────────────────────────────┐ │
│ │ Just-In-Time (JIT) │ │
│ └──────────────────────────────────┘ │
│ ┌──────────────────────────────────┐ │
│ │ Garbage Collector │ │
│ └──────────────────────────────────┘ │
│ ┌──────────────────┬───────────────┐ │
│ │ Type Checker │ Security │ │
│ └──────────────────┴───────────────┘ │
└────────────────────────────────────────┘
│
▼ (Compiled at Runtime)
[ Native Machine Code ]
│
▼
[ Operating System & Hardware ]
Example — inspecting runtime info (.NET 10)
using System.Runtime.InteropServices;
Console.WriteLine(RuntimeInformation.FrameworkDescription); // .NET 10.0.x
Console.WriteLine(RuntimeInformation.OSDescription); // e.g., Linux 6.x
Console.WriteLine(RuntimeInformation.ProcessArchitecture); // X64 / Arm64
In C#, namespaces primarily serve two crucial purposes: organizing code and preventing naming conflicts. They provide a hierarchical structure for grouping related classes, interfaces, and other types, making code easier to read, maintain, and understand.
Features:
Avoiding Name Conflicts: Namespaces help prevent naming collisions by distinguishing between types that may have the same name but are in different namespaces.
Code Organization: They provide a logical structure, making large codebases easier to manage and understand.
Improved Readability: By grouping related functionality, namespaces make code more readable and maintainable.
Access Control: Namespaces can help control the scope of class and method visibility.
Example:
namespace MyCompany.Project.Utilities
{
public class Logger
{
// Logger implementation
}
}
You can then use the using directive to access types within a namespace:
using MyCompany.Project.Utilities;
Logger logger = new Logger(); // No prefix needed now
using statement in C#?The primary purpose of the using statement in C# is to ensure automatic resource cleanup for objects that implement the IDisposable interface.
It guarantees that unmanaged resources (like file handles, database connections, or network sockets) are properly released as soon as the execution block exits, even if an unhandled exception occurs.
1. Traditional using block:
using (StreamReader file = new StreamReader("file.txt"))
{
string content = file.ReadToEnd();
// file is automatically disposed when the block exits
}
2. using declaration:
No braces needed — the object is disposed at the end of the enclosing scope. This is the preferred modern style.
using var file = new StreamReader("file.txt");
string content = file.ReadToEnd();
// file is automatically disposed here (end of method/block)
3. await using for async disposal:
For objects implementing IAsyncDisposable (e.g., async streams, HttpClient, DbContext):
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
// connection is asynchronously disposed at end of scope
Key points:
IDisposable or IAsyncDisposable.using declarations reduce nesting and are generally preferred in modern .NET code.Properties in C# are class members that provide a flexible mechanism to read, write, or compute the value of a private field. They act like a public variable to anyone using the object, but they are actually special methods called accessors (get and set). This ensures clean encapsulation and data safety.
Why Use Properties?
Types of Properties
1. Auto-Implemented Properties
Use these when you do not need special validation logic. The C# compiler automatically creates a hidden, private variable (backing field) behind the scenes
public class User
{
// A standard read-write property
public string Name { get; set; }
// A property with a default initial value
public int Level { get; set; } = 1;
}
2. Fully-Implemented Properties (With Backing Fields)
Use these when you need to execute extra logic, such as validation or formatting, when data is read or written.
public class Account
{
private decimal _balance; // Private backing field
public decimal Balance
{
get
{
return _balance;
}
set
{
// Enforce validation logic
if (value < 0)
{
throw new ArgumentException("Balance cannot be negative!");
}
_balance = value; // 'value' is the incoming data
}
}
}
3. Read-Only & Expression-Bodied Properties
You can restrict external code from modifying your values. Expression-bodied syntax (=>) makes calculated properties incredibly short
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
// Read-only calculated property using expression body
public string FullName => $"{FirstName} {LastName}";
}
4. Fine-Grained Access Control (private set and init)
You can mix access modifiers to allow anyone to read a variable, but only allow your class or initializer to set it
public class Product
{
// Can be read anywhere, but only modified inside this class
public string SKU { get; private set; }
// Can only be set during object creation (Immutable after)
public decimal Cost { get; init; }
}
An array in C# is a collection of variables of the same data type stored in contiguous memory locations. Arrays have a fixed length determined at creation, which cannot be changed later. They allow you to store multiple items (like a list of numbers or names) under a single variable name and access them using an index
Key Points:
0.Types of Arrays:
1. Single-Dimensional Array:
It stores a single row of data elements
// Declaration and initialization
int[] numbers = new int[3] { 10, 20, 30 };
foreach(int number in numbers) {
Console.WriteLine(number); // Output: 10, 20, 30
}
// Shortened syntax (Compiler infers the size)
string[] fruits = { "Apple", "Banana", "Cherry" };
// Accessing and modifying elements
int firstItem = numbers[0]; // Returns 10
fruits[1] = "Blueberry"; // Changes "Banana" to "Blueberry"
2. Multi-Dimensional Array:
Stores data in a grid format with rows and columns. Every row must have the exact same number of columns.
// 2D Array: 2 rows and 3 columns
int[,] matrix = new int[2, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
// Accessing an element (Row 1, Column 2)
int value = matrix[1, 2]; // Returns 6
3. Jagged Array (Array of Arrays):
An array of arrays, where each inner array can have a different length.
// Declaration
int[][] jaggedArray = new int[3][];
// Initializing individual rows with different sizes
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5, 6 };
jaggedArray[2] = new int[] { 7 };
// Accessing an element (Row 1, Element index 2)
int jaggedValue = jaggedArray[1][2]; // Returns 5
The main difference is that Clone() creates a brand-new array object, while CopyTo() copies elements into an already existing array.
1. Using CopyTo():
Example:
int[] source = { 10, 20, 30 };
int[] destination = new int[3];
source.CopyTo(destination, 0); // Copy
for (int i = 0; i < destination.Length; i++)
{
Console.WriteLine(destination[i]); // Output: 10, 20, 30
}
2. Using Clone():
Example:
int[] source = { 10, 20, 30 };
int[] clone = (int[])source.Clone(); // Clone
for (int i = 0; i < clone.Length; i++)
{
Console.WriteLine(clone[i]); // Output: 10, 20, 30
}
A jagged array in C# is an "array of arrays." Unlike a standard multi-dimensional array, a jagged array consists of rows where each row can have a completely different length.
Key Characteristics
int[,]) because the .NET runtime optimizes single-dimensional array access.Example:
// Declare a jagged array with 2 rows
int[][] jaggedArray = new int[2][];
// Initialize each row with different lengths
jaggedArray[0] = new int[] { 10, 20, 30 };
jaggedArray[1] = new int[] { 40, 50 };
// Accessing elements
Console.WriteLine(jaggedArray[0][1]); // Output: 20
Console.WriteLine(jaggedArray[1][0]); // Output: 40
To sort the elements of an array in descending order in C#, you can use the Array.Sort method with a custom comparer, or use LINQ for a more concise approach.
Example: Using Array.Sort with a comparer
int[] numbers = { 5, 2, 8, 1, 3 };
Array.Sort(numbers, (a, b) => b.CompareTo(a)); // Sorts in descending order
foreach (int num in numbers)
{
Console.WriteLine(num); // Output: 8 5 3 2 1
}
Example: Using LINQ
int[] numbers = { 5, 2, 8, 1, 3 };
var descending = numbers.OrderByDescending(n => n).ToArray();
foreach (int num in descending)
{
Console.WriteLine(num); // Output: 8 5 3 2 1
}
var and dynamic types?The primary difference between var and dynamic is when the data type is determined: var resolves the variable type at compile time, whereas dynamic resolves it at runtime.
var (Implicit Typing):
var variable is determined by the compiler at compile time, based on the assigned value.dynamic (Dynamic Typing):
Example:
// Using var
var score = 95; // Compiler explicitly locks 'score' as an Integer
score = "Excellent"; // COMPILE ERROR: Cannot implicitly convert string to int
// Using dynamic
dynamic response = 95; // Resolved as Integer at runtime
response = "Excellent"; // Perfectly fine; changed to String at runtime
Key Differences:
| Feature | var (Implicitly Typed) | dynamic (Dynamically Typed) |
|---|---|---|
| Type Resolution | Done by the compiler at compile time. | Done by the execution engine at runtime. |
| Type Safety | Completely type-safe. | Not type-safe at compile time. |
| Initialization | Mandatory at the moment of declaration. | Optional; can be declared empty. |
| Type Alteration | Cannot change after it is first assigned. | Can change freely to any type at any point. |
| Error Discovery | Errors are caught immediately during compilation. | Errors only trigger as exceptions during execution. |
struct in C#?A struct (structure) in C# is a user-defined value type designed to encapsulate small groups of related variables. Unlike a class, which is a reference type, a struct stores its data directly where it is declared.
At-a-Glance Comparison: Struct vs. Class
| Feature | struct | class |
|---|---|---|
| Type Category | Value type | Reference type |
| Memory Location | Stack (usually) | Heap |
| Assignment | Copies the actual data | Copies the reference (pointer) |
| Inheritance | Cannot inherit from other classes or structs | Fully supports inheritance |
| Nullability | Cannot be null by default (requires ?) |
Can be null by default |
| Default Constructor | Automatically provided (cannot be removed) | Custom ones override default |
Core Characteristics of a Struct
1. Value Type Copy Behavior
When you assign one struct variable to another, C# creates an independent copy of all the data. Modifying the copy does not alter the original structure.
public struct Point
{
public int X;
public int Y;
}
// Behavioral Example
Point p1 = new Point { X = 10, Y = 20 };
Point p2 = p1; // p2 is a brand new copy of the data
p2.X = 99; // Changing p2 does NOT change p1
Console.WriteLine(p1.X); // Outputs: 10
2. Memory and Performance
Structs are generally allocated on the stack, making creation and destruction incredibly fast. They bypass the garbage collector (GC) overhead entirely, which makes them highly efficient for critical performance loops.
3. Limitations
abstract and virtual methods?The primary difference is that an abstract method has no implementation and must be overridden, while a virtual method has a default implementation and can optionally be overridden.
Abstract Methods:
Example:
public abstract class Animal
{
// No body allowed here
public abstract void MakeSound();
}
public class Dog : Animal
{
// MUST override, or code won\'t compile
public override void MakeSound()
{
Console.WriteLine("Bark!");
}
}
Virtual Methods:
Example:
public class User
{
// Has a default implementation
public virtual void AccessDashboard()
{
Console.WriteLine("Loading standard user dashboard...");
}
}
public class Admin : User
{
// OPTIONAL override to add unique behavior
public override void AccessDashboard()
{
Console.WriteLine("Loading admin controls and dashboard...");
}
}
out and ref parameters?The primary difference between ref and out parameters is who is responsible for initializing the variable. A ref parameter requires the variable to be initialized before it is passed into the method, while an out parameter requires the method to initialize it before the method returns.
Both keywords allow you to pass arguments by reference rather than by value.
At-a-Glance Comparison
| Feature | ref Parameter | out Parameter |
|---|---|---|
| Prior Initialization | Mandatory before calling the method. | Optional; can be passed completely uninitialized. |
| Method Responsibility | Can read or modify the value freely. | Must assign a value before the method ends. |
| Primary Purpose | Modifying an existing variable's data. | Returning multiple values from a single method. |
| Direction of Data | Two-way (Data goes In and comes Out). | One-way (Data only comes Out). |
ref parameter:
ref must be initialized before it is passed to the method.out parameter:
out does not need to be initialized before being passed.out parameter before the method returns.Example:
public class Program
{
static void RefExample(ref int x)
{
x = x + 10;
}
static void OutExample(out int y)
{
y = 20; // Must assign before returning
}
public static void Main(string[] args)
{
// Using 'ref'
int a = 5;
RefExample(ref a); // a is now 15
// Using 'out'
int b;
OutExample(out b); // b is now 20
Console.WriteLine($"a = {a}"); // Output: a = 15
Console.WriteLine($"b = {b}"); // Output: b = 20
}
}
Tuple in C#?A Tuple in C# is a lightweight data structure that allows you to group multiple data elements into a single, cohesive unit. It is primarily used to return multiple values from a method without the overhead of creating a formal class or struct.
C# supports two types of tuples: modern ValueTuples (strongly recommended) and legacy System.Tuple classes.
Modern ValueTuples vs. Legacy Tuples
| Feature | Modern Tuple (ValueTuple) | Legacy Tuple (System.Tuple) |
|---|---|---|
| Type Category | Value type (struct) | Reference type (class) |
| Syntax | Simple parentheses: (int, string) | Verbose generic: Tuple<int, string> |
| Element Naming | Supported (e.g., tuple.Age) | Not supported (restricted to Item1, Item2) |
| Mutability | Mutable (values can be changed) | Immutable (read-only) |
| Performance | High (Stack allocated, zero GC allocation) | Lower (Heap allocated, creates GC pressure) |
Core Usage and Examples (Using Modern ValueTuple)
1. Creating and Accessing Named Tuples
You can assign explicit, readable names to your tuple fields instead of relying on generic properties.
// Creating a tuple with named fields
var employee = (Id: 101, Name: "Alice", IsActive: true);
// Accessing fields by their custom names
Console.WriteLine(employee.Name); // Outputs: Alice
Console.WriteLine(employee.IsActive); // Outputs: True
2. Returning Multiple Values from a Method
This is the most common use case for tuples, replacing the older out parameter pattern completely.
// Method definition returning a tuple
public (int Min, int Max) FindRange(int[] numbers)
{
// Implementation logic here...
return (12, 89);
}
// Usage
var range = FindRange(new int[] { 23, 12, 45, 89 });
Console.WriteLine($"Min is {range.Min}, Max is {range.Max}");
3. Deconstructing a Tuple
You can split a tuple's elements directly into separate, distinct variables in a single line.
var product = (Id: 50, Price: 19.99);
// Deconstruction syntax
(int prodId, double cost) = product;
Console.WriteLine(prodId); // Outputs: 50
Console.WriteLine(cost); // Outputs: 19.99
Best Practices: When to Use a Tuple
In C#, byval (by value) and byref (by reference) describe how arguments are passed to methods:
By Value (byval):
Example:
void Increment(int x)
{
x = x + 1;
}
int a = 10;
Increment(a);
Console.WriteLine(a); // Output: 10 (original value unchanged)
By Reference (byref):
Example:
void Increment(ref int x)
{
x = x + 1;
}
int a = 10;
Increment(ref a);
Console.WriteLine(a); // Output: 11 (original value changed)
An immutable string in C# is a string whose value cannot be changed after it is created. When you modify a string (such as by concatenation, replacement, or other operations), a new string object is created in memory, and the original string remains unchanged.
Why are strings immutable?:
Example:
string s1 = "Hello";
string s2 = s1;
s1 = s1 + " World"; // Creates a new string, s1 now points to "Hello World"
Console.WriteLine(s2); // Output: Hello (s2 is unchanged)
The JIT Compiler (Just-In-Time) is a core component of the .NET CLR (Common Language Runtime) that converts Intermediate Language (IL) code into native machine code at runtime, just before the code execution.
JIT Compilation Flow in .NET
C# Source Code
|
C# Complier (cs.exe)
|
MSIL (Intermediate Language)
|
Assembly (.exe/dll)
|
CLR Loads Assembly
|
JIT Compiler
|
Native Machine Code
|
CPU Executes Code
JIT Compilation Process:
csc / dotnet build using Roslyn) compiles source code into Intermediate Language (IL) and stores it in assemblies (.dll / .exe).In .NET, JIT compilation is commonly categorized into these types:
1. Normal JIT
Compiles a method the first time it is called, then caches the native code for later calls. This is the standard behavior.
2. Pre-JIT
Compiles IL to native code ahead of execution (historically via NGen; in modern .NET, ReadyToRun and Native AOT are the relevant ahead-of-time approaches).
3. Econo JIT (historical)
Used limited memory by compiling methods on demand and discarding compiled code when possible. This is obsolete in modern .NET.
Note: In modern .NET (Core/.NET 5+), the main runtime JIT engine is RyuJIT, and it uses tiered compilation:
In C#, value-type variables hold their data directly in memory, unlike reference types which store a reference to the data. When assigned, value-type variables create a copy of the data, meaning changes to one variable do not affect others, except in cases where ref or out modifiers are used.
Characteristics:
int?).int, float, bool, char, struct, and enum) and user-defined structs and enums.0 for numeric types, false for bool).Example:
int number = 42; // Integral value type
double price = 19.99; // Floating-point value type
bool isActive = true; // Boolean value type
char letter = 'A'; // Character value type
DateTime today = DateTime.Now; // Struct (user-defined value type)
Summary Table:
| Feature | Value Type Example | Behavior |
|---|---|---|
| Storage | int x = 5; |
Stores value directly in variable |
| Assignment | int y = x; |
Copies value, not reference |
| Nullability | int? z = null; |
Nullable only with ? syntax |
| Default Value | int x; |
Defaults to 0 |
| Inheritance | struct |
Cannot inherit from another struct/class |
A parameter in C# is a variable defined in a method, constructor, or indexer declaration that receives a value (called an argument) when the method is called. Parameters allow you to pass data into methods so they can operate on different values.
C# introduced specialized parameter modifiers aimed at optimizing memory and performance, particularly when passing value types
in Parameters: Passes an argument by reference but makes it strictly read-only. It prevents copying large struct variables while guaranteeing the method cannot modify the original data.
out Variables: Allows you to declare an output parameter directly inside the method call argument list (e.g., int.TryParse("123", out int result)), eliminating the need for separate variable declarations.
ref readonly Parameters: Combines reference passing with read-only constraints, allowing methods to accept both references and values (like literals or constants) without creating unnecessary copies.
Optional Parameters: Allows you to assign a default value to a parameter inside the method signature (e.g., void Log(string msg, int level = 1)). Callers can omit this argument entirely.
Named Parameters: Allows you to pass arguments by matching their explicit name followed by a colon (e.g., Log(msg: "Error", level: 3)). This lets you pass arguments in any order or skip certain optional parameters.
Dynamic Parameters: Uses the dynamic keyword to bypass compile-time type checking. The exact type and operations are resolved at runtime, which is highly useful for interoperability.
Primary Constructor Parameters: Introduced for standard classes and structs (extending C# 9 records), these let you define parameters directly in the class declaration line. They automatically map to fields and are visible throughout the entire scope of the class.
Example:
using System;
namespace ParameterDemo
{
// C# 12 Primary Constructor Parameter
// 'id' and 'name' are available throughout the entire class scope
public class User(int id, string name)
{
public void DisplayUser() => Console.WriteLine($"User {id}: {name}");
}
// A large struct to demonstrate performance optimization
public struct LargeDataPoint
{
public double X;
public double Y;
public double Z;
}
class Program
{
static void Main(string[] args)
{
// 1. Primary Constructor Example
User newUser = new User(101, "Alice");
newUser.DisplayUser();
// 2. Named and Optional Parameters Example
// We omit 'prefix', so it uses the default value "LOG:"
// We use named parameters to pass 'message' and 'level' out of order
WriteLog(level: 3, message: "System initialized.");
// 3. Inline 'out' Parameter Example
// The variable 'parsedValue' is declared right inside the method call
if (int.TryParse("456", out int parsedValue))
{
Console.WriteLine($"Successfully parsed out value: {parsedValue}");
}
// 4. 'in' Parameter Example
LargeDataPoint point = new LargeDataPoint { X = 1.0, Y = 2.0, Z = 3.0 };
// Passed by reference (no copy made), but read-only
ProcessCoordinates(in point);
// 5. Dynamic Parameter Example
// Bypasses compile-time checking; resolved at runtime
dynamic dynamicString = "Hello Dynamic World!";
PrintLength(dynamicString);
}
// Method with an optional parameter (prefix)
static void WriteLog(string message, int level, string prefix = "LOG:")
{
Console.WriteLine($"{prefix} [{level}] {message}");
}
// 'in' modifier guarantees 'data' cannot be modified inside this method
static void ProcessCoordinates(in LargeDataPoint data)
{
// data.X = 10.0; // ERROR: This line would fail to compile!
Console.WriteLine($"Processing coordinate X: {data.X}");
}
// Dynamic parameter resolves operations at runtime
static void PrintLength(dynamic item)
{
// The compiler does not check if '.Length' exists until this runs
Console.WriteLine($"The length of the item is: {item.Length}");
}
}
}
In C#, literals are fixed values assigned directly to variables or constants in code. They represent constant values of various data types.
Types of literals in C#:
1. Integer Literals
10, -42, 0xFF (hexadecimal), 0b1010 (binary), 123U (unsigned), 123L (long).U (unsigned), L (long), UL (unsigned long).2. Floating-Point Literals
3.14, 2.5e2 (scientific notation), 1.5F (float), 2.7D (double), 1.2M (decimal).F or f (float), D or d (double), M or m (decimal).3. Character Literals
'A', '\n', '\u0041'.4. String Literals
"Hello", "C#\nBasics".@ — preserve escape sequences and line breaks, e.g., @"C:\Users\Name".$ — embed expressions, e.g., $"Hello, {name}!"."""...""". No escape sequences needed, multi-line friendly.// Raw string literal (C# 11+)
string json = """
{
"name": "Pradeep",
"age": 30
}
""";
// Raw interpolated string
string name = "Pradeep";
string greeting = $"""Hello, {name}! Welcome to "C# 14".""";
u8 — produces a ReadOnlySpan<byte> for zero-copy UTF-8 data, ideal for networking and file I/O.ReadOnlySpan<byte> utf8Hello = "Hello"u8;
5. Boolean Literals
true and false.6. Null Literal
null.Examples:
int age = 25; // Integer literal
double pi = 3.14159; // Floating-point literal
char letter = 'A'; // Character literal
string name = "Alice"; // String literal
bool isActive = true; // Boolean literal
object obj = null; // Null literal
In C#, the equivalent of a sub-procedure (from languages like VB/VBA) is a method with void return type, while a function is a method that returns a value.
Both perform actions, but functions allow you to use their result elsewhere in your code, while subroutines/sub procedures simply execute and return control.
Difference :
Example:
// Function: returns an int
int Add(int a, int b)
{
return a + b;
}
// Sub-procedure: returns nothing (void)
void PrintSum(int a, int b)
{
Console.WriteLine(a + b);
}
In C#, string and StringBuilder both handle text, but string is immutable, and StringBuilder is mutable. This means that when you modify a string, a new string object is created, while with StringBuilder, you can modify the object in place without creating new objects.
1. string:
Immutable: Once created, a string cannot be changed. Any operation that appears to modify a string (such as concatenation or replacement) actually creates a new string object in memory.
Performance: Frequent modifications (like concatenation in loops) can lead to performance issues due to repeated allocations and garbage collection.
Usage: Best for scenarios where the text does not change often.
Example:
string s = "Hello";
s += " World"; // Creates a new string object
2. StringBuilder:
Mutable: Designed for scenarios where you need to modify the text repeatedly. Changes are made to the same object, avoiding unnecessary allocations.
Performance: More efficient for repeated modifications, such as appending or inserting text in loops.
Usage: Recommended when building or modifying large or dynamic strings.
Example:
using System.Text;
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World"); // Modifies the existing object
string result = sb.ToString();
When to use which?
string when you have a fixed set of text data, perform very few modifications, or are simply concatenating a small, known number of strings.StringBuilder when you are modifying text an unknown number of times, such as inside a for or foreach loop, or when building massive blocks of text dynamically.In C#, early binding (also known as static binding) resolves method calls at compile time, while late binding (also known as dynamic binding) resolves method calls at runtime.
Early binding offers better performance and type safety due to compile-time checking, while late binding provides more flexibility but with potential runtime overhead, especially when using reflection, according to various sources.
Early Binding:
Example:
// Early binding example
MyClass obj = new MyClass();
obj.MyMethod(); // Compiler knows about MyMethod at compile time
Late Binding:
Example 1: Late binding using dynamic:
using System;
public class Greeter
{
public void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
class Program
{
static void Main()
{
dynamic obj = new Greeter();
obj.SayHello("Pradeep"); // Method resolved at runtime
// Output: Hello, Pradeep!
// The type can change at runtime
obj = 42;
Console.WriteLine(obj + 8); // Output: 50
}
}
Example 2: Late binding using Reflection:
using System;
using System.Reflection;
public class Calculator
{
public int Add(int a, int b) => a + b;
}
class Program
{
static void Main()
{
// Load type and invoke method at runtime — no compile-time knowledge needed
Type type = typeof(Calculator);
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("Add");
object result = method.Invoke(instance, new object[] { 10, 20 });
Console.WriteLine($"Result: {result}"); // Output: Result: 30
}
}
Real-World Usage
An indexer in C# is a special type of property that allows objects of a class or struct to be indexed just like arrays, using the square bracket [] syntax. Indexers enable you to access elements in an object using an index, making custom classes behave like collections.
Key Benefits:
obj[index] brackets instead of calling explicit methods.Example:
public class MyCollection
{
private string[] data = new string[5];
// Indexer declaration
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
// Usage
var collection = new MyCollection();
collection[0] = "Hello";
Console.WriteLine(collection[0]); // Output: Hello
In C#, object is the ultimate base class checked at compile-time, var is shorthand for a specific compile-time type, and dynamic bypasses compile-time checking entirely until runtime..
Key Differences
1. object
object variable.object. You must cast to the actual type to access members.Example:
object obj = "Hello";
// Console.WriteLine(obj.Length); // Error: 'object' does not contain 'Length'
Console.WriteLine(((string)obj).Length); // OK after casting
2. var:
Example:
var message = "Hello"; // message is string
// message = 123; // Error: cannot assign int to string
Console.WriteLine(message.Length); // OK
3. dynamic:
Example:
dynamic value = "Hello";
Console.WriteLine(value.Length); // OK at runtime
value = 123;
// Console.WriteLine(value.Length); // Runtime error: 'int' does not contain 'Length'
Detailed Comparison:
| Feature | object | var | dynamic |
|---|---|---|---|
| Type Resolution | Compile time | Compile time (inferred) | Runtime |
| Type Safety | Yes (with casting) | Yes | No |
| Flexibility | High (but verbose) | Medium | Highest |
| Member Access | Requires casting | Direct (after inference) | Direct (runtime) |
| Use Case | General base type, APIs | When type is obvious or anonymous types | Interop, dynamic scenarios |
Managed code is code that runs under the control of the .NET Common Language Runtime (CLR). The CLR provides services such as automatic memory management (garbage collection), type safety, exception handling, and security. Examples include C# and VB.NET code compiled for the .NET runtime.
Unmanaged code is code that runs directly on the operating system, outside the control of the CLR. It is responsible for its own memory management and resource cleanup. Examples include code written in C or C++ and compiled to native machine code, as well as COM components and Win32 API calls.
Key Differences:
| Managed Code | Unmanaged Code |
|---|---|
| Runs under CLR (.NET runtime) | Runs directly on OS |
| Automatic memory management (GC) | Manual memory management |
| Type safety and security checks | No built-in type safety |
| Exception handling by CLR | Must handle exceptions manually |
| Platform-independent (via CLR) | Platform-dependent |
Summary:
Managed code is safer and easier to maintain, while unmanaged code offers more control and performance but requires careful resource management.
An Object Pool in C# is a creational design pattern that improves performance by reusing objects instead of repeatedly creating and destroying them. It involves maintaining a pool of pre-initialized objects, readily available for use when needed. This reduces memory allocation and garbage collection overhead, leading to faster execution, especially when dealing with frequently created and destroyed objects.
Benefits:
Example:
// Simple generic object pool example
public class ObjectPool<T> where T : new()
{
private readonly Stack<T> _objects = new Stack<T>();
public T GetObject()
{
return _objects.Count > 0 ? _objects.Pop() : new T();
}
public void ReturnObject(T item)
{
_objects.Push(item);
}
}
// Usage
var pool = new ObjectPool<StringBuilder>();
StringBuilder sb = pool.GetObject();
sb.Append("Hello, Object Pool!");
pool.ReturnObject(sb);
.NET Built-in Support:
.NET Core provides System.Buffers.ObjectPool<T> and ArrayPool<T> for pooling arrays and other objects.
In C#, lazy evaluation defers the execution of code until its result is actually needed, while eager evaluation executes code immediately upon encountering it
1. Eager Evaluation: Values or expressions are computed immediately when they are assigned or called.
Example: Standard variable assignments and most method calls.
int x = GetValue(); // GetValue() is called immediately
2. Lazy Evaluation: Computation is deferred until the value is actually needed (accessed for the first time).
Example: Using Lazy<T>, IEnumerable<T> with yield return, or LINQ queries.
Lazy<int> lazyValue = new Lazy<int>(() => GetValue());
// GetValue() is not called until lazyValue.Value is accessed
IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
}
// Numbers are generated as you iterate
Comparison:
| Feature | Eager Evaluation | Lazy Evaluation |
|---|---|---|
| Execution Time | Immediately | On demand |
| Use cases | Always-needed values | Expensive/optional values |
| LINQ Examples | .ToList(), ToArray(), Count() |
.Where(), Select(), Skip() |
| Memory Usage | Higher | Lower |
| Performance | Better when results are needed repeatedly | Better for large datasets |
In C#, the checked and unchecked blocks are used to control how the runtime handles arithmetic overflow for integral types (like int, long, etc.).
checked block: Forces the runtime to throw an OverflowException if an arithmetic operation results in a value outside the range of the data type.
unchecked block: Suppresses overflow checking, so if an overflow occurs, the result wraps around (default behavior in most cases).
Example:
int max = int.MaxValue;
try
{
// Checked block: will throw OverflowException
checked
{
int result = max + 1;
}
}
catch (OverflowException)
{
Console.WriteLine("Overflow detected!");
}
// Unchecked block: will not throw, wraps around
unchecked
{
int result = max + 1;
Console.WriteLine(result); // Output: -2147483648
}
When to use:
checked when you want to ensure that overflows are caught and handled.unchecked when performance is critical and you are sure overflows are not an issue.You can also use the checked and unchecked keywords as expressions:
int result = checked(max + 1); // Throws OverflowException
int result2 = unchecked(max + 1); // Wraps around
The primary difference is that typeof returns a System.Type object representing metadata about a type, whereas sizeof returns an integer indicating the memory footprint (in bytes) of an unmanaged type
1. typeof() Operator:
System.Type object for a given type.Example: typeof() is commonly used with Reflection
if(obj.GetType() == typeof(Employee))
{
Console.WriteLine("Employee Object");
}
2. sizeof() Operator:
Example:
Console.WriteLine(sizeof(byte)); // Output: 1
Console.WriteLine(sizeof(short)); // Output: 2
Console.WriteLine(sizeof(int)); // Output: 4
Console.WriteLine(sizeof(long)); // Output: 8
Console.WriteLine(sizeof(char)); // Output: 2
Summary Table:
| Operator | Purpose | Returns | Usage Example |
|---|---|---|---|
| typeof | Get type metadata | Type object | typeof(int) |
| sizeof | Get size in bytes (value types) | Integer (bytes) | sizeof(int) |
Note:
typeof() works for all types (value and reference).sizeof() works only for value types and may require unsafe context for custom structs.Widening conversion (Implicit) converts a smaller data type into a larger data type without losing data. Narrowing conversion (Explicit) converts a larger data type into a smaller data type, which can cause data loss.
1. Widening Conversion (Implicit Conversion):
Example: int to long, float to double.
int num = 100;
long result = num; // Widening: int to long (implicit)
float flt = num; // Widening: int to float (implicit)
Console.WriteLine(result); // Output: 100
Console.WriteLine(flt); // Output: 100
Common Widening Conversions
| From | To |
|---|---|
| byte | short, int, long, float, double, decimal |
| short | int, long, float, double, decimal |
| int | long, double, decimal |
| float | double |
2. Narrowing Conversion (Explicit Conversion):
Example: double to int, long to short.
double x = 123.45;
int y = (int)x; // Narrowing: double to int (explicit), y = 123
long big = 1000;
short small = (short)big; // Narrowing: long to short (explicit)
Console.WriteLine(y); // Output: 123
Console.WriteLine(small); // Output: -31072
To view a compiled .NET Assembly (a .dll or .exe file), you must decompile it using an assembly inspector tool to reconstruct the original C# code or read its Intermediate Language (IL) metadata. Because C# compiles into a standardized byte-code, these tools can instantly deconstruct an assembly back into readable source code.
1. Using IL Disassembler:
IL Disassembler is a tool provided with the .NET SDK to view the contents of an assembly (DLL or EXE).
Steps:
ildasm YourAssembly.dll
2. Using ILSpy (Third-Party Tools):
.dll or .exe file in these tools to view C# code, metadata, and resources.Example:
MyLibrary.dll
|-------Services
|-------EmployeeService
|------GetEmployee()
|------SaveEmployee()
3. Using Visual Studio:
4. Using Reflection in Code:
You can use reflection to inspect an assembly programmatically:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Assembly asm = Assembly.LoadFrom("MyAssembly.dll");
foreach (Type type in asm.GetTypes())
{
Console.WriteLine(type.FullName);
}
}
}
In C#, multilingual applications are software programs that leverage the built-in System.Globalization namespace to dynamically adapt their user interface, text, and formatting based on a user's langua
learning-zone/csharp-basics is a public repo on GitHub by learning-zone. C# Basics.
It declares the MIT license on GitHub.
Its maker tagged it for macOS, Windows and Linux, or as Docker or cross-platform. That is declared by the maker; Take My Repo has not tested it.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-08-09. GitHub counts 0 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
This repository contains a collection of C# code examples designed to demonstrate various programming concepts and best practices. Each example is structured to provide clear, concise, and practical insights into different aspects of C# programming.
《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持简中、繁中、English、日本語,提供 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 等代码实现
Bitwarden infrastructure/backend (API, database, Docker, etc).

Hi All, In this repo I'll add some links with study topics to prepare for .NET interviews in a month.
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/learning-zone/csharp-basicsTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.