Virtual and Abstract in .net
so today I will what is virtual and abstract with one real-life example.
when you need to override some method you should use virtual or abstract.
virtual methods are already implemented, if you need to change that behavior, you are able to override
abstract methods are not implemented, you have to override them.
by the way, the default definition is non-virtual
Example:
so you have base repository, and you have also entity repositories like product repository, sales repository etc.
in your base you have crud operations and the most common methods are implemented in you base repository, you will derivered entity repositories from base, when you do that you need to implement all methods in entity repository.but if declare your base repo as base you dont need to implement all
public class ExperienceRepository : Repository<Experience>, IExperienceRepository
{
public ExperienceRepository(ApplicationDbContext context) : base(context)
{
}
}
so if you need to change of behaviors in your base, lets assume you want to change getall method.
public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
you should add virtual first, then go to your entity repository and override it.