I found the following example, to which I have a follow up question.
the existing code from the question is
public interface IRepository<T> where T : EntityObject
{
RepositoryInstructionResult Add(T item);
RepositoryInstructionResult Update(T item);
RepositoryInstructionResult Delete(T item);
}
public class Repository<T> : IRepository<T> where T : EntityObject
{
virtual RepositoryInstructionResult Add(T item)
{ //implementation}
virtual RepositoryInstructionResult Update(T item);
{ //implementation}
virtual RepositoryInstructionResult Delete(T item);
{ //implementation}
}
public class BarRepository : Repositorybase<Bar>
{
public override RepositoryInstructionResult Update(Bar item);
{
//Call base method if needed
//Base.Update(item);
//implement your custom logic here
}
}
what I would like to do is change the Update method to something like
public class BarRepository : Repositorybase<Bar>
{
// T is of Type Bar
public override RepositoryInstructionResult Update(T item);
{
//implement your custom logic here
}
}
Question: is there a way to expose the generic type in BarResposity : Repositorybase<Bar>
to the methods in BarRepository?
looking for a better alternative to "search and replace" when building out the concrete class (eg make a copy of BarRespository as FooRepository and change all references from Bar to Foo). I would rather change the type in one place only.
(edit) Usage needs to remain as
var obj = new BarRepository();
It's a bit of a hack, but you could use a using
alias to define the entity type:
using MyType = Bar;
public class BarRepository : Repositorybase<MyType>
{
public override RepositoryInstructionResult Update(MyType item);
{
return base.Update(item);
}
}
Now when you copy to Foo.cs
, you can just change the using directive to
using MyType = Foo;
But, I would look to try and reuse as much generic code as possible, as it's not clear at all what MyType
is just by looking at the methods. There's nothing wrong with a find.replace to define a new repository type that customizes actions - you just want to keep the repeated to a minimum.