Thursday, May 29, 2025

Insights from Steve Jobs on Programming and Technology


1. Programming and Creativity

“Everybody in this country should learn how to program a computer because it teaches you how to think.”

— Steve Jobs

Jobs believed programming wasn’t just a technical skill but a fundamental way of thinking—one that fosters creativity and problem-solving.



2. Technology as a Tool for Art

“It’s in Apple’s DNA that technology alone is not enough. It’s technology married with liberal arts, married with the humanities, that yields us the results that make our hearts sing.”

— Steve Jobs

He saw programming and technology as mediums to create products with elegance, beauty, and human-centered design, not just functionality.


3. Simplicity in Software and Design

“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.”

— Steve Jobs

For Jobs, programming and software design should strive for simplicity and clarity to truly empower users.


4. The Power of Interactivity

“Design is not just what it looks like and feels like. Design is how it works.”

— Steve Jobs

In programming, this meant creating interfaces and systems that are intuitive and seamless — bridging human interaction with technology.


5. On Innovation and Programming

“Innovation distinguishes between a leader and a follower.”

— Steve Jobs

Programming, in Jobs’ view, was a core ingredient for innovation, enabling companies to lead rather than follow.


6. Programming as a Liberal Art

“I think everybody in this country should learn how to program a computer because it teaches you how to think.”

— Steve Jobs, 1995 interview

He advocated that computer science should be a fundamental part of education, similar to art or literature.


7. Focus on the User Experience

“Get closer than ever to your customers. So close that you tell them what they need before they realize it themselves.”

— Steve Jobs

In programming, this means anticipating user needs and creating software that delights.


8. On Software Quality

“Quality is more important than quantity. One home run is much better than two doubles.”

— Steve Jobs

He prioritized writing clean, powerful code that delivers impact over lots of mediocre features.

Wednesday, May 28, 2025

How to Use log4net for Logging in C# Applications

Logging is a crucial aspect of software development, helping you track issues, monitor behavior, and maintain applications more effectively. log4net is a powerful, flexible logging library for .NET applications, inspired by the Java-based log4j. This guide shows how to integrate log4net into a C# project with a working example.

Key Features of log4net

  • Easy to configure via XML or code.
  • Supports multiple logging targets (file, console, event log, etc.).
  • Thread-safe logging.
  • Fine-grained control over log levels: DEBUG, INFO, WARN, ERROR, FATAL.

Step-by-Step Guide:


1. Install log4net via NuGet

Open the NuGet Package Manager Console and run:

Install-Package log4net

2. Add Configuration in App.config or Web.config

Add the following inside your configuration file:

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs\\app.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>
Note: Ensure the Logs folder exists or your application has permission to create/write to it.

3. Initialize and Use log4net in C# Code

Here’s a simple example in Program.cs:

using System;
using log4net;
using log4net.Config;
using System.Reflection;

class Program
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    static void Main(string[] args)
    {
        XmlConfigurator.Configure(); // Loads config from App.config
        log.Info("Application started");

        try
        {
            int a = 10, b = 0;
            int result = a / b;
        }
        catch (Exception ex)
        {
            log.Error("An error occurred", ex);
        }

        log.Warn("This is a warning");
        log.Debug("Debug message");
        log.Fatal("Fatal error simulation");

        Console.WriteLine("Done. Check the Logs folder.");
    }
}

Output Example

This configuration writes logs to Logs\app.log with entries like:

2025-05-28 10:35:14,553 [1] INFO  Program - Application started
2025-05-28 10:35:14,559 [1] ERROR Program - An error occurred
System.DivideByZeroException: Attempted to divide by zero.
   at Program.Main(String[] args)

How to Securing Passwords Against Quantum Computers

Why special care for passwords?

Passwords are stored as hashes, not encrypted, to prevent attackers from recovering the original password if the database leaks. However, with quantum computers, classical password hashing algorithms could become easier to brute force.

Quantum Threats to Password Hashing

  • Grover’s algorithm speeds up brute-force attacks quadratically on symmetric cryptography and hash functions.
  • This means attackers could try roughly the square root of password guesses in the same time compared to classical brute force.
  • Password hashing needs to be computationally expensive and memory-hard, making each guess costly on quantum hardware.

Best Practices for Quantum-Resistant Password Hashing

  1. Use slow, memory-hard hashing algorithms designed for password storage like Argon2, scrypt, or bcrypt.
  2. Always use a unique random salt per password.
  3. Use sufficiently large parameters (iterations, memory, CPU cost) to slow brute forcing.
  4. Use constant-time verification to avoid timing attacks.

C# Examples for Quantum-Resistant Password Hashing:


1. Argon2 — Recommended for quantum resistance

// Install NuGet Package: Install-Package Isopoh.Cryptography.Argon2
using Isopoh.Cryptography.Argon2;
using System;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Hash the password with Argon2id
        string hash = Argon2.Hash(password);

        Console.WriteLine($"Argon2 Hash: {hash}");

        // Verify the password
        bool valid = Argon2.Verify(hash, password);
        Console.WriteLine($"Password valid? {valid}");
    }
}

2. bcrypt — Widely used, moderately quantum-resistant

// Install NuGet Package: Install-Package BCrypt.Net-Next
using BCrypt.Net;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate bcrypt hash
        string hash = BCrypt.Net.BCrypt.HashPassword(password);

        Console.WriteLine($"bcrypt Hash: {hash}");

        // Verify the password
        bool valid = BCrypt.Net.BCrypt.Verify(password, hash);
        Console.WriteLine($"Password valid? {valid}");
    }
}

3. scrypt — Memory-hard, good for resisting quantum attacks

// Install NuGet Package: Install-Package CryptSharpOfficial
using CryptSharp;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate scrypt hash
        string hash = Crypter.Scrypt.Crypt(password);

        Console.WriteLine($"scrypt Hash: {hash}");

        // Verify the password
        bool valid = Crypter.CheckPassword(password, hash);
        Console.WriteLine($"Password valid? {valid}");
    }
}

4. PBKDF2 — Built-in, less memory-hard, but still usable with high iteration count

using System;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        string password = "MyQuantumSafePassword123!";

        // Generate a 16-byte salt
        byte[] salt = new byte[16];
        using (var rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(salt);
        }

        // Derive a 256-bit key using PBKDF2 with 100,000 iterations and SHA256
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256);
        byte[] hash = pbkdf2.GetBytes(32);

        // Convert to base64 for storage
        string saltBase64 = Convert.ToBase64String(salt);
        string hashBase64 = Convert.ToBase64String(hash);

        Console.WriteLine($"Salt: {saltBase64}");
        Console.WriteLine($"Hash: {hashBase64}");

        // Verification
        var pbkdf2Verify = new Rfc2898DeriveBytes(password, salt, 100_000, HashAlgorithmName.SHA256);
        byte[] hashToVerify = pbkdf2Verify.GetBytes(32);

        bool valid = CryptographicOperations.FixedTimeEquals(hash, hashToVerify);
        Console.WriteLine($"Password valid? {valid}");
    }
}

Tuesday, May 13, 2025

Top 25 ASP.NET Interview Questions and Answers

1. What is ASP.NET?

Answer: ASP.NET is a web application framework developed by Microsoft. It allows developers to build dynamic web applications, websites, and web services. It is part of the .NET framework and supports multiple languages like C# and VB.NET.

2. What is the difference between ASP.NET WebForms and ASP.NET MVC?

Answer: ASP.NET WebForms is a traditional event-driven model for developing web applications, whereas ASP.NET MVC follows a Model-View-Controller architecture. MVC offers more control over HTML, provides better separation of concerns, and is more testable.

3. What is a Page Life Cycle in ASP.NET?

Answer: The page life cycle in ASP.NET includes the following stages:

  • Page Request
  • Start
  • Initialization
  • Load
  • Postback
  • Render
  • Unload

4. What is the difference between a postback and a callback in ASP.NET?

Answer: A postback occurs when a page sends data to the server to reload and re-render the page. A callback is a partial page update, typically performed using AJAX, which sends data to the server without refreshing the entire page.

5. What are HTTP handlers and HTTP modules?

Answer: HTTP handlers are responsible for processing requests for specific resources (like images or custom data). HTTP modules are classes that can handle events during the HTTP request/response cycle and can be used for tasks like authentication, logging, and caching.

6. What is ViewState in ASP.NET?

Answer: ViewState is a mechanism in ASP.NET used to store the values of controls between postbacks. It helps maintain the state of the page and its controls during the page lifecycle.

7. What is a Master Page in ASP.NET?

Answer: A Master Page is used to provide a consistent layout and appearance across all pages of a web application. It allows developers to define a common template for pages, which can be shared across multiple content pages.

8. What is caching in ASP.NET?

Answer: Caching in ASP.NET is the process of storing frequently accessed data in memory to reduce the load on the server and improve performance. There are different types of caching, such as Output Caching, Data Caching, and Application Caching.

9. What is Web.config in ASP.NET?

Answer: Web.config is a configuration file used in ASP.NET applications to define settings for the application, such as database connections, security configurations, and custom error handling.

10. What are the different types of authentication in ASP.NET?

Answer: ASP.NET supports several types of authentication, including:

  • Forms Authentication: Used for web-based applications to authenticate users with a login form.
  • Windows Authentication: Used for intranet applications where users are authenticated using Windows credentials.
  • Passport Authentication: Used to authenticate users with Microsoft's passport service.
  • Custom Authentication: Allows developers to implement their own authentication mechanism.

11. What is Routing in ASP.NET MVC?

Answer: Routing in ASP.NET MVC is a mechanism that maps incoming HTTP requests to the appropriate controller and action method. It is based on URL patterns defined in the RouteConfig file.

12. What is the difference between a Controller and a View in ASP.NET MVC?

Answer: A Controller in ASP.NET MVC is responsible for handling user requests, interacting with the model, and selecting the appropriate view. A View is responsible for rendering the HTML output to the user.

13. What are Action Filters in ASP.NET MVC?

Answer: Action Filters are attributes that allow you to add extra functionality to controller actions. They can be used for tasks like logging, caching, or validation before or after the execution of an action method.

14. What is the purpose of the TempData collection in ASP.NET MVC?

Answer: TempData is used to pass data between controllers. Unlike ViewData and ViewBag, TempData persists data only for the duration of a single request. It is ideal for passing messages or data that needs to be available across redirects.

15. What is the difference between ViewData and ViewBag?

Answer: Both ViewData and ViewBag are used to pass data from controllers to views. ViewData is a dictionary object, while ViewBag is a dynamic object. ViewBag is more flexible and simpler to use because it doesn't require explicit type casting.

16. What is Dependency Injection in ASP.NET Core?

Answer: Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC). It allows for injecting dependencies into a class rather than hard-coding them, making the code more modular, testable, and maintainable. ASP.NET Core has built-in support for DI.

17. What is Entity Framework in ASP.NET?

Answer: Entity Framework (EF) is an Object-Relational Mapper (ORM) that allows developers to interact with a database using .NET objects, eliminating the need for writing SQL queries manually. EF supports both Code First and Database First approaches.

18. What is the difference between GET and POST methods in ASP.NET?

Answer: The GET method is used to request data from a server, and the data is sent in the URL. The POST method is used to send data to the server for processing, and the data is sent in the request body, making it more secure.

19. What is AJAX in ASP.NET?

Answer: AJAX (Asynchronous JavaScript and XML) is a technique used to update parts of a web page without reloading the entire page. In ASP.NET, it can be implemented using controls like UpdatePanel and client-side JavaScript.

20. What is the Global.asax file in ASP.NET?

Answer: Global.asax is an optional file used to define application-level events, such as Application_Start, Application_End, Session_Start, and Session_End. It is used to manage global application-level tasks like authentication, logging, and caching.

21. What is MVC 5 in ASP.NET?

Answer: MVC 5 is the latest version of ASP.NET MVC, which introduced new features like attribute routing, enhanced support for mobile devices, and improvements to the authentication and authorization system.

22. What is the use of IHttpHandler in ASP.NET?

Answer: IHttpHandler is an interface used to handle custom HTTP requests in ASP.NET. It allows developers to process incoming requests for resources like images, files, or custom data.

23. What are Bundling and Minification in ASP.NET?

Answer: Bundling is the process of combining multiple files (like CSS or JavaScript files) into a single file, while minification is the process of removing unnecessary characters (like spaces and comments) from those files to reduce their size and improve performance.

24. What are the benefits of using Web API over WCF?

Answer: Web API is simpler to use, more lightweight, and provides better support for RESTful services. It is better suited for modern web applications, while WCF is more suitable for SOAP-based communication.

25. What are the different types of sessions in ASP.NET?

Answer: ASP.NET provides several ways to store session data:

  • In-Process Session: Stores session data in memory on the web server.
  • State Server Session: Stores session data on a separate server.
  • SQL Server Session: Stores session data in a SQL Server database.
  • Custom Session: Allows you to define your own session storage mechanism.

Performance Tuning for .NET Applications

Performance tuning is a critical aspect of developing high-performance .NET applications. Whether you're working on an enterprise-level application or a smaller system, optimizing your application's performance ensures a better user experience and system reliability. Below are some key techniques and tools that can help you optimize your .NET applications.

1. Identify Performance Bottlenecks

Before optimizing, it's important to first identify where the performance issues are occurring. Common areas that might need attention include CPU usage, memory usage, database access, and I/O operations.

You can use tools like BenchmarkDotNet to perform accurate benchmarking or dotTrace for profiling and finding memory leaks and CPU hotspots.

Example:

using BenchmarkDotNet.Attributes;

public class MyBenchmark
{
    [Benchmark]
    public void SomeMethod()
    {
        // Code to benchmark
    }
}

2. Optimizing Memory Usage

Excessive memory usage can significantly degrade your application's performance. To improve memory management, follow these strategies:

  • Use Value Types Wisely: Avoid boxing/unboxing of value types by using structures (struct) when appropriate.
  • Use Object Pooling: For objects that are expensive to create, consider object pooling to reuse them instead of constantly allocating new ones.

Example of a simple object pool:

public class ObjectPool<T> where T : new()
{
    private readonly Queue<T> _pool = new();

    public T Rent()
    {
        return _pool.Count > 0 ? _pool.Dequeue() : new T();
    }

    public void Return(T item)
    {
        _pool.Enqueue(item);
    }
}

3. Avoiding Blocking Code with Asynchronous Programming

Asynchronous programming helps keep your applications responsive. Avoid blocking calls such as Thread.Sleep() and Task.Wait() that can hinder performance, especially in web applications.

Make sure to use async/await whenever possible to allow non-blocking operations.

Example:

public async Task<string> GetDataAsync()
{
    var data = await _httpClient.GetStringAsync("https://example.com");
    return data;
}

4. Efficient Database Access

Inefficient database queries can significantly impact performance. You can improve database performance by:

  • Minimizing database calls by caching frequently accessed data.
  • Using parameterized queries to avoid SQL injection and improve query plan reuse.
  • Optimizing queries to avoid unnecessary joins, subqueries, and large result sets.

Example of a parameterized query:

using (var command = new SqlCommand("SELECT * FROM Users WHERE Id = @id", connection))
{
    command.Parameters.AddWithValue("@id", userId);
    var reader = await command.ExecuteReaderAsync();
}

5. Caching Frequently Used Data

Caching can dramatically reduce the need for redundant calculations or database queries. Use memory cache for short-lived data and distributed caching for long-lived data or large-scale applications.

Example using MemoryCache:

MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

public void CacheData(string key, object value)
{
    cache.Set(key, value, TimeSpan.FromMinutes(5));
}

public object GetCache(string key)
{
    return cache.Get(key);
}

6. Optimizing Garbage Collection (GC)

The .NET Garbage Collector (GC) automatically manages memory, but there are ways to optimize its performance:

  • Use structs for small, short-lived objects instead of classes to avoid unnecessary heap allocations.
  • Explicitly trigger GC when you know a large amount of memory has been used up.
  • Minimize the creation of large object heap (LOH) objects, as LOH objects can lead to fragmentation.

Example to force a manual GC collection:

GC.Collect();

7. Use of Profilers for Fine-Tuning Performance

Tools like dotMemory or dotTrace can help identify memory leaks and CPU bottlenecks by providing in-depth reports on memory usage, CPU performance, and thread contention.

Example:

dotMemory.MemoryProfiler.Analyze();

These tools allow you to isolate issues and optimize your code for performance.


8. Avoiding Unnecessary Boxing/Unboxing

Boxing and unboxing operations convert value types to reference types and vice versa, causing performance overhead. In performance-sensitive applications, minimizing boxing can help reduce unnecessary allocations.

Example of boxing:

object obj = 5; // Boxing
int i = (int)obj; // Unboxing

Try to use value types (int, double, structs) directly where possible.


9. Multi-threading for CPU-bound Tasks

If your application is CPU-bound, consider using multi-threading to perform calculations in parallel. The Task Parallel Library (TPL) can be used to split tasks across multiple CPU cores to maximize processing power.

Example:

public async Task<int> ProcessDataAsync()
{
    return await Task.WhenAll(
        Task.Run(() => DoWork1()),
        Task.Run(() => DoWork2())
    );
}

Conclusion

By following these performance tuning techniques, you can significantly improve the performance of your .NET applications. From avoiding memory leaks and optimizing database access to leveraging asynchronous programming and multi-threading, there are various strategies that can help optimize your app's performance.

Effective performance tuning also requires continuous monitoring and optimization, so always keep an eye on your application’s metrics and update the code as necessary.

Top 20 SQL Server Interview Questions and Answers

1. What is SQL Server?

Answer: SQL Server is a relational database management system (RDBMS) developed by Microsoft. It is used to store and manage data, and it uses Structured Query Language (SQL) for managing and querying data.

2. What are the different types of joins in SQL Server?

Answer: SQL Server supports several types of joins to combine data from two or more tables:

  • Inner Join: Returns records that have matching values in both tables.
  • Left Join: Returns all records from the left table and matched records from the right table.
  • Right Join: Returns all records from the right table and matched records from the left table.
  • Full Outer Join: Returns all records when there is a match in either left or right table.
  • Cross Join: Returns the Cartesian product of both tables (every combination of rows).

3. What is normalization in SQL Server?

Answer: Normalization is the process of organizing data in a database to avoid redundancy and dependency. The goal is to ensure that the database is free from insertion, update, and deletion anomalies. It involves dividing large tables into smaller, manageable tables and defining relationships between them.

4. What are indexes in SQL Server?

Answer: Indexes are database objects that speed up the retrieval of rows from a table. They can be created on one or more columns of a table. There are two main types of indexes in SQL Server:

  • Clustered Index: Determines the physical order of data rows in the table.
  • Non-Clustered Index: Creates a separate structure from the data table and contains pointers to the data.

5. What is a stored procedure in SQL Server?

Answer: A stored procedure is a precompiled collection of one or more SQL statements that can be executed as a single unit. Stored procedures are used to encapsulate logic and improve performance by reducing network traffic.

6. What is a trigger in SQL Server?

Answer: A trigger is a special type of stored procedure that automatically executes when an event such as an INSERT, UPDATE, or DELETE occurs on a specified table or view. Triggers can be used for enforcing business rules or for logging.

7. What is the difference between UNION and UNION ALL?

Answer: Both UNION and UNION ALL are used to combine results from two or more queries:

  • UNION: Removes duplicate rows from the result set.
  • UNION ALL: Includes all rows from the result set, including duplicates.

8. What is a primary key?

Answer: A primary key is a column (or combination of columns) that uniquely identifies each row in a table. It must contain unique values and cannot contain NULL values. Each table can have only one primary key.

9. What is a foreign key?

Answer: A foreign key is a column (or combination of columns) used to establish a relationship between two tables. It refers to the primary key of another table and ensures referential integrity between the two tables.

10. What is a view in SQL Server?

Answer: A view is a virtual table that is defined by a query. It can be used to simplify complex queries, aggregate data, or provide a security layer by restricting access to specific columns or rows.

11. What is a subquery?

Answer: A subquery is a query nested inside another query. It can be used to perform operations such as filtering or calculating values. Subqueries can be classified as correlated or non-correlated depending on whether they depend on the outer query.

12. What is a transaction in SQL Server?

Answer: A transaction is a sequence of one or more SQL operations that are executed as a single unit. Transactions ensure data consistency and integrity by adhering to the ACID properties: Atomicity, Consistency, Isolation, and Durability.

13. What are the ACID properties?

Answer: ACID stands for the four key properties of a transaction:

  • Atomicity: Ensures that a transaction is fully completed or fully rolled back.
  • Consistency: Ensures that a transaction brings the database from one valid state to another.
  • Isolation: Ensures that concurrent transactions do not interfere with each other.
  • Durability: Ensures that once a transaction is committed, its effects are permanent, even in the case of a system failure.

14. What is the difference between DELETE and TRUNCATE?

Answer: Both DELETE and TRUNCATE are used to remove data from a table, but:

  • DELETE: Removes rows one by one and logs each row removal. It can be rolled back and can have conditions applied.
  • TRUNCATE: Removes all rows from the table without logging individual row deletions. It cannot be rolled back and does not fire triggers.

15. What is an index scan and index seek?

Answer: An index scan is when SQL Server reads all the rows in an index to satisfy a query, while an index seek is when SQL Server uses the index to directly access the rows that satisfy the query's conditions.

16. What are the differences between a clustered index and a non-clustered index?

Answer: A clustered index determines the physical order of data rows, while a non-clustered index creates a separate structure that contains pointers to the data rows. A table can have only one clustered index but multiple non-clustered indexes.

17. What is a deadlock in SQL Server?

Answer: A deadlock occurs when two or more sessions are blocking each other and cannot proceed because each session is waiting for a resource held by another. SQL Server automatically detects and resolves deadlocks by terminating one of the transactions.

18. What is the purpose of the WITH (NOLOCK) hint?

Answer: The WITH (NOLOCK) hint allows SQL Server to read data without acquiring locks, which can improve performance. However, it can lead to dirty reads, where uncommitted changes may be read.

19. What are common SQL Server data types?

Answer: Common data types in SQL Server include:

  • INT: Stores integer values.
  • VARCHAR: Stores variable-length character strings.
  • DATETIME: Stores date and time values.
  • DECIMAL: Stores fixed-point numbers.
  • BIT: Stores Boolean values (0 or 1).

20. What is a CTE (Common Table Expression)?

Answer: A CTE is a temporary result set defined within the execution scope of a SELECT, INSERT, UPDATE, or DELETE statement. CTEs are used to simplify complex queries and make the code more readable.

What's New in C# 12

C# 12 introduces several features that enhance syntax clarity, reduce boilerplate, and improve performance, particularly for object initialization and collections. One such feature is Primary Constructors, which brings concise constructor syntax to regular classes and structs—previously only available for records.

Here is an example of how to use Primary Constructors in C# 12:
 
public class Product(string name, decimal price) 
{ 
	public void PrintDetails() 
	{ 
	Console.WriteLine($"Product: {name}, Price: {price:C}"); 
	} 
} 
In this example, the Product class uses a primary constructor, where the parameters name and price are directly available throughout the class. This eliminates the need to manually declare private fields and assign values in a traditional constructor.

Another powerful addition in C# 12 is Collection Expressions, which simplify collection initialization and allow combining or spreading multiple collections.

Here is an example:
 
int[] baseNumbers = [1, 2, 3]; 
int[] moreNumbers = [..baseNumbers, 4, 5]; 
List<string> 
names = [ "Alice", "Bob", "Charlie" ]; 
In this snippet, the [..baseNumbers, 4, 5] syntax merges baseNumbers with additional elements into a new array. The use of square brackets and the spread operator (..) simplifies working with collections and makes the code more expressive.

C# 12 also introduces default parameter values for lambdas, making functional programming more flexible:

 
Func<string, string> greet = (string name = "Guest") => $"Hello, {name}!"; 
Console.WriteLine(greet()); // Output: Hello, Guest! 
Here, the lambda function greet provides a default value for name, allowing it to be called with or without arguments.

Another notable enhancement is the ability to create type aliases for any type—including arrays, tuples, and generic types:

 
using IntList = List<int>; 
using NameAgeTuple = (string Name, int Age); 
IntList scores = new() { 90, 80, 85 }; 
NameAgeTuple person = ( "David", 34 ); 
This improves readability and maintainability by allowing complex types to be referenced using simpler names.

Finally, the new [Experimental] attribute allows marking APIs as experimental to communicate instability to consumers:
 [Experimental("This feature is still under development")] 
void NewFeature() { } 
This is especially helpful in SDKs and library development where features may evolve over time.