C# equivalent of <? extends Type>? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm working in C#. I created an interface in my code which is called EntityInterface. I wrote this function:
private void Save(List<EntityInterface> entities)
{ ... }
Elsewhere in my code, I have a variable which is defined as List<Job>. The Job class is a class that implements EntityInterface.
I cannot pass my list of Job objects to the Save method. The compiler complains that the parameter is of the wrong type, because List<Job> is not the same as List<EntityInterface>.
I need to modify the function to express the idea that the parameter can be a "list of any object that implements EntityInterface". I have searched around but can't find an example of how to do this.

Your model should look something like this:
using System.Collections.Generic;
public interface IEntity
{
void Save<T>(List<T> entities) where T : IEntity;
}
public class Job : IEntity
{
void IEntity.Save<T>(List<T> entities) { }
}
public class TargetImpl : IEntity
{
void IEntity.Save<T>(List<T> entities) { }
}
and as a test to step through:
using System.Collections.Generic;
using Xunit;
public class UnitTest1
{
[Fact]
public void Test1()
{
IEntity ientity = new TargetImpl();
ientity.Save(new List<Job>());
}
}
One caveat being the example above implements the IEntity interface explicitly (for brevity) as such child implementations must be explicitly referenced via that interface. For a similar but subtly different implementation you could also do:
public class Job : IEntity
{
public void Save<T>(List<T> entities) where T : IEntity { }
}
public class TargetImpl : IEntity
{
public void Save<T>(List<T> entities) where T : IEntity { }
}
and the test impl can (optionally) change to :
[Fact]
public void Test1()
{
targetImpl ientity = new TargetImpl();
ientity.Save(new List<Job>());
}

Related

Best way to implement similar methods of two different classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have two classes (A and B) which implements the same interface (I) in C#. The interface have 5 methods to implement. Implementations of two of those methods are almost the same in both A and B except each implemetation uses a different variable. Here is the abstract layout of my classes.
class A : I
{
Folder folder;
void method()
{
//implementation uses ``folder``
}
class B : I
{
List list;
void method()
{
//implementation uses ``list``
}
}
Because the implementation of Method is the same (except the one parameter) I want to have implement Method only once. What is the best solution according of design patterns? one simple option is to define a third class which implements Methodand takes one parameter (either list or folder) and then call it within the Method of A and B. Any other solution?
------------Edit---------------
I don't want my Method to get any extra parameter. Under such circumstances, isn't static util class a better option than defining an abstract class?
You can create a shared abstract base class which takes a T generic parameter and implements I<T>. That same T will be passed to Method, which will be implemented in the base class:
public interface I<T>
{
void Method(T t);
}
public abstract class Base<T> : I<T>
{
public Base(T t)
{
this.param = t;
}
private readonly T param;
public void Method()
{
// Do stuff
}
}
public class A : Base<Folder>
{
public A(Folder folder) : base(folder)
{ }
}
public class B : Base<List>
{
public B(List list) : base(list)
{ }
}
public class Folder { }
public class List { }
Now, you can do:
static void Main()
{
var a = new A(new Folder());
a.Method();
var b = new B(new File());
b.Method();
}
One option is to use an abstract class instead of an interface. Of course this class must be generic.
Second option is to extract method to "static utils" class and in both use this "utils". But this assumes that list and folder are instances of same interface.
In my opinion the first option is the best one.
If the method's implementations differ only by a variable's type consider using Template Method pattern combined with a generic base class.
abstract class Base<T> : I
{
public void method()
{
var items = GetItems();
HandleItems(items);
}
protected abstract IEnumerable<T> GetItems();
void HandleItems(IEnumerable<T> items)
{
// do something with a sequence
foreach(var item in items) Console.WriteLine(item);
}
}
class A : Base<FolderItem>
{
Folder folder;
protected overrides IEnumerable<FolderItem> GetItems() {return folder.Items;}
}
class B : Base<ListItem>
{
List list;
protected overrides IEnumerable<ListItem> GetItems() {return list.Items;}
}

Casting Generic to abstract base - covariance

The code below gives compile time error:
Error 170 Cannot convert type 'Tests.ChangeListener' to 'Tests.BaseListener'
How do I get this to compile?
namespace Tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ShouldCompile()
{
BaseListener<IChange> listener = (BaseListener<IChange>)new ChangeListener();
}
}
public interface IChange
{
}
public interface ISpecificChange : IChange
{
}
public abstract class BaseListener<T>
where T : IChange
{
}
public class ChangeListener : BaseListener<ISpecificChange>
{
}
}
Since you can't do contravariance or covaraiance (ie in and out) on an abstract class you'll probably want an interface for your listener. Modifying the above to look like this allows it to compile (note entities not mentioned remain the same as the original code - attributes stripped to save me needing to import references while testing):
public class UnitTest1
{
public void ShouldCompile()
{
IListener<IChange> listener = new ChangeListener();
}
}
public interface IListener<out T> {}
public abstract class BaseListener<T> : IListener<T>
where T : IChange
{
}
This is obviously adding in a step that you don't currently have and may not be able to use for whatever reasons but it is the simplest way to get the code compiling and I think do what you want.

Interface vs Class : Defining methods [duplicate]

This question already has answers here:
Interface vs Base class
(38 answers)
Closed 8 years ago.
I'm a bit new to OO programming and I'm trying to understand all facets of this kind of practice : inheritance, polymorphism and such, but there's a thing my brain DOESN'T WANT to fully understand: Interfaces.
I can understand the benefits of using interfacing instead of class-inheritance (mostly because a class can't inherit from multiple parents) but here's where I'm stuck:
Let's say I have something like this:
/** a bunch of interfaces **/
public interface IMoveable
{
void MoveMethod();
}
public interface IKilleable()
{
void KillMethod();
}
public interface IRenderable()
{
void RenderMethod();
}
/** and the classes that implement them **/
public class ClassOne : IMoveable
{
public void MoveMethod() { ... }
}
public class ClassTwo: IMoveable, IKilleable
{
public void MoveMethod() { ... }
public void KillMethod() { ... }
}
public class ClassThree: IMoveable, IRenderable
{
public void MoveMethod() { ... }
public void RenderMethod() { ... }
}
public class ClassFour: IMoveable, IKilleable, IRenderable
{
public void MoveMethod() { ... }
public void KillMethod() { ... }
public void RenderMethod() { ... }
}
By using interfaces here, I would have to declare MoveMethod, KillMethod and RenderMethod each time, in each classes... That means duplicating my code. There must be something wrong, because I don't find this really practical.
So should I implement interfaces only on a few classes? Or should I find a way to mix inheritance and interfaces?
Interfaces are like a contract to a class.. If some class states that it supports such an interface, it must have it's method defined as you properly sampled. Interfaces are great to expose common things that don't easily cross different class implementations.
Now, from your samples, you may be best to do a combination to prevent duplicate code by subclassing from a class and ALSO an interface. So you can get parent-structure code constant and expand as needed.
/** Based on same interfaces originally provided... and the classes that implement them **/
public class ClassOne : IMoveable
{
public void MoveMethod() { ... }
}
public class ClassTwo: ClassOne, IKilleable
{
// Move Method is inherited from ClassOne, THEN you have added IKilleable
public void KillMethod() { ... }
}
public class ClassThree: ClassOne, IRenderable
{
// Similar inherits the MoveMethod, but adds renderable
public void RenderMethod() { ... }
}
public class ClassFour: ClassTwo, IRenderable
{
// Retains inheritance of Move/Kill, but need to add renderable
public void RenderMethod() { ... }
}

How to figure out which repository to call for different implementations of an interface?

I am just starting in DDD and have a question regarding interfaces of objects and repositories. Suppose I have the following objects
public interface IPerson { ... }
public class Student
{
double gpa;
...
}
public class Teacher
{
double salary; ...
}
then I also have two repositories such as
public class StudentRepository :IRepository { public void Save(Student) }
public class TeacherRepository :IRepository { public void Save(Teacher) }
My question is, suppose I have a list of IPerson objects called persons, is there a way where I can just do something like repository.Save(persons) ? Without having to use reflection to figure out what type the IPerson actually is.
I currently have another class
PersonRepository :IRepository
{
public void Save(IPerson person)
{
if(Person is Student)
{
new StudentRepository.Save(person as Student);
}
else if(Person is Teacher)
{ ....}
}
}
Then I can call personRepository.Save(persons);
However this doesnt feel like an optimal way to structure things. How can I improve this design?
Thanks
EDIT:
What I'm looking for is, say I receive an IPerson object called person. I do not necessarily know what implementation it is, I just want to call repository.Save(person) and have it call the correct repository. Is there a way to do this without using some sort of switch statement with reflection?
Consider using generic repository
class Repository<T> :IRepository<T>
{
public void Save(T entity)
{
...
}
}
Usage
IRepository<Student> repo1 = new Repository<Student>();
repo1.Save(new Student());
IRepository<Teacher> repo2 = new Repository<Teacher>();
repo2.Save(new Teacher());
Next you can use IoC container and DI just to pass repositories around instead of creating them
At the top level, say in the main method or global.asax
IRepository<Student> studentRepo = IoC.Current.Resolve<IRepository<Student>>();
Later in a class that needs to save data, pass IRepository<Student> studentRepo into constructor
class Foo
{
private IRepository<Student> repo
Foo(IRepository<Student> repo)
{
this.repo = repo;
}
public void Save(Student s)
{
repo.Save(s);
}
}
EDIT
You can move a save operation to the IPerson<T>
class Person<T> : IPerson<T>
{
private IRepository<T> repo;
Person(IRepository<T> repo)
{
this.repo = repo;
}
public void Save()
{
repo.Save<T>();
}
}
So when you derive Teacher and Student from Person<T> you pass correspondent T, like
class Student : Person<Student>
{
private IRepository<Student> repo;
Person(IRepository<Student> repo):base(repo)
{
...
}
}
This shall give you the ability to work with List without Reflection or switch kung fu.
You can potentially have a method with C# generics
interface Repository<TEntity> where TEntity : class {
void Save(TEntity entity);
}
But I would discourage having generic (as in generalized, not C# generics) repositories. Repository interface should be domain driven and specific to your entity. Please consider this article by Greg Young.
It is also not clear why you have interfaces for you entities (IPerson). Interfaces are usually created at the seam of the application. Are you planning to have more than one implementation of IPerson?
Two possible approaches.
First, interfaces specific for domain types
interface IStudentRepository
interface ITeacherRepository
class StudentRepository : IStudentRepository
class TeacherRepository : ITeacherRepository
Second, a generic interface
interface IRepository<T>
class StudentRepository : IRepository<Student>
class TeacherRepository : IRepository<Teacher>

How to do Generic Repository with Dependency Injection [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have set up my generic repository as follows:
public interface IRepository<T> : IDisposable where T : Entity
{
T GetById(int id);
}
public abstract class Repository<T> : IRepository<T> where T : Entity
{
protected readonly SqlDbContext _context = new SqlDbContext();
public T GetById(int id)
{
return _context.Set<T>().Find(id);
}
}
To enable dependency injection in my MVC app i also create a Product interface since the signature differs. This is also the case for the other repositories.
public interface IProductRepository : IRepository<Product>
{
IEnumerable<Product> GetDiscountedProducts();
}
And the implementation (note the inheritance)
public class ProductRepository : Repository<Product>, IProductRepository
{
public IEnumerable<Product> GetDiscountedProducts()
{
return _context.Set<Product>().Where(x=>x)...
}
}
Finally the repository gets injected into the MVC controller using unity
public HomeController(IProductRepository repository)
{
}
Is it just me or is this inheritance chain a bit messy here? Is there any way to improve this design?
I would suggest to avoid IProductRepository for this particular case (when simply adding single and very specific method) and enhance original IRepository interface as shown below:
public interface IRepository<TEntity> : IDisposable
where TEntity : Entity
{
TEntity GetById(int id);
IEnumerable<TEntity> List(IFilterCriteria criteria);
}
and then implement
public sealed class ProductDiscountFilterCriteria : IFilterCriteria
{
// ...
}
but in such case you've to define some logic to transform criteria to an query, it could be a LINQ Expression as you'are already using LINQ. If such creteria expression approach is complex for your case - I would suggest to stick with approach you've proposed.
EDIT: IFilterCriteria is simply Query Object pattern implementation
interface IFilterCriteria<TQuery>
{
TQuery ToQuery();
}
public sealed class ProductDiscountFilterCriteria : IFilterCriteria<DynamicExpression>
{
public decimal Discount { get; private set; }
public DynamicExpression ToQuery()
{
// build expression for LINQ clause Where("Discount" > this.Discount)
}
}
OR raw SQL criteria builder:
public sealed class ProductDiscountFilterCriteria : IFilterCriteria<string>
{
public decimal Discount { get; private set; }
public string ToQuery()
{
// simplified
return "WHERE Discount < " + this.Discount;
}
}
So then you would be able to use it like:
var products = productRepository.List<Product>(
new DiscountFilterCriteria { Discount = 50 });
Dynamic LINQ examples and articles:
Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
Dynamic LINQ (A little more dynamic)
Dynamic LINQ Part 2 (Evolution)

Categories