0% found this document useful (0 votes)
9 views18 pages

C# Concepts 5

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views18 pages

C# Concepts 5

Uploaded by

musabinshabeer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

C# Concepts

Generics
C#: Generics

• Definition: Generics allow you to define classes, interfaces, and


methods with a placeholder for the type of data they store or use.
This promotes code reusability, type safety, and performance.
Generics: Purpose
• Reusability: Write code once and use it with different data
types.

• Type Safety: Errors are caught at compile-time rather than at


runtime.

• Performance: Avoids the need for boxing/unboxing or type


casting.
Generic Classes: Example – Generic Repository

public interface IRepository<T> where T : class


{
Task<T> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
}
Generic Classes: Example – Generic Repository

public class Repository<T> : IRepository<T> where T : class


{
private readonly AppDbContext _context;
private readonly DbSet<T> _dbSet;

public Repository(AppDbContext context)


{
_context = context;
_dbSet = _context.Set<T>();
}
Generic Classes: Example – Generic Repository

public async Task<T> GetByIdAsync(int id)


{
return await _dbSet.FindAsync(id);
}

public async Task<IEnumerable<T>> GetAllAsync()


{
return await _dbSet.ToListAsync();
}
Generic Classes: Example – Generic Repository

public async Task AddAsync(T entity)


{
await _dbSet.AddAsync(entity);
await _context.SaveChangesAsync();
}

public async Task UpdateAsync(T entity)


{
_dbSet.Update(entity);
await _context.SaveChangesAsync();
Generic Classes: Example – Generic Repository

public async Task DeleteAsync(int id)


{
var entity = await GetByIdAsync(id);
if (entity != null)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync();
}
}
}
Generic Classes: Example – Usage

public interface IUnitOfWork


{
IRepository<User> Users { get; }
IRepository<Product> Products { get; }
Task SaveChangesAsync();
}
Generic Classes: Example – Usage
public class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext _context;
private IRepository<User> _users;
private IRepository<Product> _products;

public UnitOfWork(AppDbContext context)


{
_context = context;
}
Generic Classes: Example – Usage
public IRepository<User> Users => _users ??= new Repository<User>(_context);
public IRepository<Product> Products => _products ??= new
Repository<Product>(_context);

public async Task SaveChangesAsync()


{
await _context.SaveChangesAsync();
}
}

// Register in DI container
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
Generic Repository - Benefits
• Code Reusability: Single repository implementation for multiple
entities.

• Type Safety: Ensures that operations are performed on the


correct entity types.

• Maintainability: Changes in repository logic affect all entities


uniformly.
Generic Methods Example: Generic
Swap Method
public static class Utility
{
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
Generic Methods Example: Generic
Swap Method
// Usage
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10;
Utility.Swap(ref x, ref y);
Console.WriteLine($"x: {x}, y: {y}"); // Output: x: 10, y: 5

string str1 = "Hello", str2 = "World";


Utility.Swap(ref str1, ref str2);
Console.WriteLine($"str1: {str1}, str2: {str2}"); // Output: str1: World, str2:
Hello
}
C#: Generic Constraints

• Definition: Constraints limit the types that can be used as generic


type parameters, enabling you to specify required features of the
types.
Generic Constraints Example -
Where T : class
public class Service<T> where T : class
{
public void DoSomething(T obj)
{
// Implementation
}
}
Generic Constraints
Common Constraints:

• 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 parameterless constructor.

• where T : BaseClass - T must inherit from BaseClass.


Generic Constraints Example with
Multiple Constraints:
public class Repository<T> where T : class, IEntity, new()
{
// Implementation
}

Explanation:
• T must be a reference type (class).
• T must implement IEntity.
• T must have a parameterless constructor (new()).

You might also like