Saturday, 9 August 2025

yield in c# 
 Certainly! The yield keyword in C# is used to simplify the creation of iterators. 
It allows you to return each element of a collection one at a time, without the need for an explicit collection or temporary storage. 
Here's a breakdown of how it works: 
 yield return: 
 This statement is used to return each element one at a time. 
 When the yield return statement is reached, the current location in the code is remembered, and execution is paused until the next element is requested. Example:
IEnumerable<int> GetEvenNumbers(int max)
{
    for (int i = 0; i <= max; i += 2)
    {
        yield return i;
    }
}
yield break:
This statement is used to end the iteration early. It stops the iteration and exits the method. Example:
IEnumerable<int> GetNumbersUntilNegative(int[] numbers)
{
    foreach (int number in numbers)
    {
        if (number < 0)
        {
            yield break;
        }
        yield return number;
    }
}
Benefits: Simplifies Code: Reduces the need for explicit state management and temporary collections.

Lazy Evaluation: Elements are generated on-the-fly, which can improve performance and reduce memory usage. 
Usage: Commonly used in methods that return IEnumerable<int> or IEnumerator<int>. Can be used in both synchronous and asynchronous methods (with IAsyncEnumerable). 
 In summary, the yield keyword in C# provides a convenient way to create iterators, making your code cleaner and more efficient.
Share:

Dispose Pattern (Advanced) for both managed and unmanaged resources

🔄 Dispose Pattern (Advanced) If your class holds both managed and unmanaged resources, implement the full dispose pattern:

public class MyResource : IDisposable
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);  // Prevent finalizer from running
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Dispose managed resources
            }

            // Release unmanaged resources
            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(false);  // Finalizer only releases unmanaged resources
    }
}

📋 Best Practices ✅ Always use using for short-lived disposable objects. ✅ Implement IDisposable if your class owns disposable fields. ✅ Call GC.SuppressFinalize(this) in Dispose() if you have a finalizer. ✅ Make Dispose() idempotent — safe to call multiple times.
Share:

Saturday, 19 April 2025

Custom Immutable Class

Creating an immutable class in C# ensures that once an instance is created, its state cannot be modified. This is useful for Creating reliable and thread-safe objects. Here’s how you can achieve this: 

1- Use readonly fields and initialize them through the constructor. 
2- Avoid setters for properties. 
3- Mark the class as sealed to prevent inheritance (optional). Here’s a simple example:
public sealed class ImmutablePerson
{
    public readonly string FirstName { get; }
    public readonly string LastName { get; }

    public ImmutablePerson(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public string GetFullName()
    {
      return  $"{FirstName} {LastName}"
    }
}

var person = new ImmutablePerson("John", "Doe");
 Console.WriteLine(person.GetFullName());
In this example: 
1- The FirstName and LastName properties are read-only. 
2- The only way to set FirstName and LastName is through the constructor. 
3- The class is sealed to prevent modification through inheritance.
Share: