How to write an interface for a generic method - c#

I have the class PlayersCollection and I want to interface it in IWorldCollection.
The probleme is about writing the declaration in the interface which cause me this error :
Assets/Scripts/Arcane/api/Collections/ItemsCollection.cs(17,22): error CS0425:
The constraints for type parameter `T' of method
`Arcane.api.ItemsCollection.Get<T>(int)
must match the constraints for type parameter `T' of
interface method `Arcane.api.IWorldCollection.Get<T>(int)'.
Consider using an explicit interface implementation instead
Here is my class and my interface. How to write a generic method implementation with a class constraint ?
public class PlayersCollection : IWorldCollection
{
public Dictionary<Type, object> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, object>();
}
public T Get<T>(int id) where T: PlayerModel
{
var t = typeof(T);
if (!Collection.ContainsKey(t)) return null;
var dict = Collection[t] as Dictionary<int, T>;
if (!dict.ContainsKey(id)) return null;
return (T)dict[id];
}
}
}
public interface IWorldCollection
{
T Get<T>(int id) where T : class;// Work when I change "class" to "PlayerModel".
}
Big thanks for your help :)

It seems to me that the following will meet the requirements, by pushing the generic type parameter up to the class/interface level:
public class PlayersCollection<T> : IWorldCollection<T> where T : PlayerModel
{
public Dictionary<Type, T> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, T>();
}
public T Get(int id)
{
var t = typeof(T);
if (!Collection.ContainsKey(t)) return null;
var dict = Collection[t] as Dictionary<int, T>;
if (!dict.ContainsKey(id)) return null;
return (T)dict[id];
}
}
public interface IWorldCollection<T> where T : class
{
T Get(int id);
}
If I have missed something in the requirements, please let me know.

I'm not sure why you need this interface, but maybe this will help:
public class PlayersCollection<T> : IWorldCollection<T> where T:PlayerModel
{
public Dictionary<Type, object> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, object>();
}
public T Get(int id)
{
...
}
}
public interface IWorldCollection<T> where T:class
{
T Get(int id);
}

Try this:
public class PlayersCollection : IWorldCollection<PlayerModel>
{
public Dictionary<Type, object> Collection;
public PlayersCollection()
{
Collection = new Dictionary<Type, object>();
}
public PlayerModel Get<PlayerModel>(int id)
{
///
}
}
}
public interface IWorldCollection<T>
{
T Get<T>(int id);
}
In your case, in the class implementing your interface, you adding more condition for your class:
where T : class in the interface
where T: PlayerModel in the class
If, for some reason, you need to add a constraint into your interface, you need to add an interface or base class, which will be placed to the interface declaration, and you'll have to derive from it in your PlayerModel class, like this:
public abstract class Model
{
}
public class PlayerModel : Model
{
}
public interface IWorldCollection<T> where T : Model
{
T Get<T>(int id);
}
public class PlayersCollection : IWorldCollection<PlayerModel>
{
///
public PlayerModel Get<PlayerModel>(int id)
{
///
}
}
}

Related

Generic inheritance constraint on class parameter fails

public class Test<T>
{
private T something;
public Test<NewT> Cast<NewT>() where T : NewT
{
return new Test<NewT>() { something = this.something };
}
}
VS Error: 'Test.Cast()' does not define type parameter 'T'
Why does this happens?
This is because you can only constrain type parameters that are defined in the method. T is not defined in the method, but in the class, so you can't constrain it like that.
You can, however, make Cast an extension method:
// in some static class
public static Test<NewT> Cast<T, NewT>(this Test<T> test) where T : NewT {
return new Test<NewT>() { something = test.something };
}
This means that something has to be made public, which can sometimes be undesirable. You can alternatively do something like this:
public class Test<T>
{
public T Something { get; private set; }
public Test(T something) {
Something = something;
}
}
// in some static class
public static Test<NewT> Cast<T, NewT>(this Test<T> test) where T : NewT
{
return new Test<NewT>(test.Something);
}

Interface with abstract class

I have to write a class called Vehicle with many attributes (e.g. size, seats, color, ...) and also I have two more classes to write called Trunk and Car with their own attributes.
So I wrote it:
// Vehicle.cs
abstract public class Vehicle
{
public string Key { get; set; }
...
}
// Car.cs
public class Car : Vehicle
{
...
}
// Trunk.cs
public class Trunk : Vehicle
{
...
}
After that, I wrote an Interface:
// IVehicleRepository.cs
public interface IVehicleRepository
{
void Add(Vehicle item);
IEnumerable<Vehicle> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(Vehicle item);
}
So I was thinking that I could use something like this:
// CarRepository.cs
public class CarRepository : IVehicleRepository
{
private static ConcurrentDictionary<string, Car> _cars =
new ConcurrentDictionary<string, Car>();
public CarRepository()
{
Add(new Car { seats = 5 });
}
public IEnumerable<Car> GetAll()
{
return _cars.Values;
}
// ... I implemented the other methods here
}
But, I got errors:
error CS0738: 'CarRepository' does not implement interface member 'IVehicleRepository.GetAll()'. 'CarRepository.GetAll()' cannot implement 'IVehicleRepository.GetAll()' because it does not have the matching return type of 'IEnumerable<'Vehicle>'.
So, how I can do it?
Your CarRepository isn't implementing the method. These two are not the same:
public IEnumerable<Car> GetAll()
IEnumerable<Vehicle> GetAll()
These are two different types and when you derive from the interface you have to implement it exactly. You can just implement it this way:
public IEnumerable<Vehicle> GetAll()
{
// Cast your car collection into a collection of vehicles
}
However the better way would be to make it a generic interface of: (The downside is that the two different implementations type again are two different types so see if that is what you want)
public interface IVehicleRepository<TVehicle> {}
public class CarRepository : IVehicleRepository<Car> {}
A more complete version:
public interface IVehicleRepository<TVehicle> where TVehicle : Vehicle
{
void Add(TVehicle item);
IEnumerable<TVehicle> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(TVehicle item);
}
public class CarRepository : IVehicleRepository<Car>
{
private static ConcurrentDictionary<string, Car> _cars =
new ConcurrentDictionary<string, Car>();
public CarRepository()
{
Add(new Car { seats = 5 });
}
public IEnumerable<Car> GetAll()
{
return _cars.Values;
}
}
You could make the IVehicleRepository generic:
public interface IVehicleRepository<T> where T : Vehicle
{
void Add(T item);
IEnumerable<T> GetAll();
Vehicle Find(string key);
Vehicle Remove(string key);
void Update(T item);
}
and then implement the classes like this:
public class CarRepository : IVehicleRepository<Car>
{
private static ConcurrentDictionary<string, Car> _cars =
new ConcurrentDictionary<string, Car>();
public CarRepository()
{
Add(new Car { seats = 5 });
}
public IEnumerable<Car> GetAll()
{
return _cars.Values;
}
}
But you will then still have the problem that a CarRepository is a IVehicleRepository<Car> while a TruckRepository would be a IVehicleRepository<Truck>. And these two interfaces are different types and only assignable to each other if the have the correct variance.

C# multiple generic in inheritance

How it can be fixed? Why I can not to use this constructions?
using System;
public class Program
{
public interface IReadParamModel{ }
public interface IReadResultModel{ }
public interface IWriteParamModel{ }
public interface IWriteResultModel{ }
public interface IDataReader<TParam, TResult> where TParam : IReadParamModel where TResult : IReadResultModel
{
TResult Get(TParam param);
}
public interface IDataWriter<TParam, TResult> where TParam : IWriteParamModel where TResult : IWriteResultModel
{
TResult Write(TParam param);
}
public abstract class BaseReportService<TReader, TWriter>
where TReader : IDataReader<IReadParamModel, IReadResultModel>
where TWriter : IDataWriter<IWriteParamModel, IWriteResultModel>
{
TWriter writer;
TReader reader;
}
public class ReaderParamModel : IReadParamModel { }
public class ReadResultModel : IReadResultModel { }
public class WriteParamModel : IWriteParamModel { }
public class WriteResultModel : IWriteResultModel { }
public class DataReader : IDataReader<ReaderParamModel, ReadResultModel>
{
public ReadResultModel Get(ReaderParamModel param) { return null; }
}
public class DataWriter : IDataWriter<WriteParamModel, IWriteResultModel>
{
public IWriteResultModel Write(WriteParamModel param){ return null; }
}
public class ReportService : BaseReportService<DataReader, DataWriter>
{
}
}
Compilation error (line 46, col 15): The type 'Program.DataReader' cannot be used as type parameter 'TReader' in the generic type or method 'Program.BaseReportService'. There is no implicit reference conversion from 'Program.DataReader' to 'Program.IDataReader'.
Compilation error (line 46, col 15): The type 'Program.DataWriter' cannot be used as type parameter 'TWriter' in the generic type or method 'Program.BaseReportService'. There is no implicit reference conversion from 'Program.DataWriter' to 'Program.IDataWriter'.
The problem is, that IDataReader<IReadParamModel, IReadResultModel> and IDataReader<ReaderParamModel, ReadResultModel> are incompatible types. In order to make them compatible, co-/contravariance would be needed, but with TResult Get(TParam param);, TParam would be contravariant and TResult would be covariant. This means, there is no way to make the two interfaces compatible with their current usage.
The choices are, to use the interfaces directly if access to the implementation properties is not required or to use the concrete types as additional generic parameters. The following code contains three sections that demonstrate the different designs, based on the co-/contravariant IDataReader interface.
The code is restricted to the Reader part, since the examples for reader and writer are quite similar. The Test method is used to highlight some differences in the actually available types at different inheritance levels.
public interface IReadParamModel { }
public interface IReadResultModel { }
public class ReaderParamModel : IReadParamModel { }
public class ReadResultModel : IReadResultModel { }
public interface IDataReader<in TParam, out TResult>
where TParam : IReadParamModel
where TResult : IReadResultModel
{
TResult Get(TParam param);
}
// First variant - much interface usage
public class DataReader_1 : IDataReader<IReadParamModel, ReadResultModel>
{
public ReadResultModel Get(IReadParamModel param) { return null; }
}
public abstract class BaseReportService_1<TReader>
where TReader : IDataReader<IReadParamModel, IReadResultModel>
{
protected TReader reader;
// input is interface, reader.Get result is interface
protected virtual IReadResultModel Test(IReadParamModel param)
{
var result = reader.Get(param);
return result;
}
}
public class ReportService_1 : BaseReportService_1<DataReader_1>
{
// input is interface, reader.Get result is concrete class
protected override IReadResultModel Test(IReadParamModel param)
{
var result = reader.Get(param);
return result;
}
}
// Second variant - less interface usage, more generic parameters
public class DataReader_2 : IDataReader<ReaderParamModel, ReadResultModel>
{
public ReadResultModel Get(ReaderParamModel param) { return null; }
}
public abstract class BaseReportService_2<TReader, TReaderParam>
where TReader : IDataReader<TReaderParam, IReadResultModel>
where TReaderParam : IReadParamModel
{
protected TReader reader;
// input is concrete class, reader.Get result is interface
protected virtual IReadResultModel Test(TReaderParam param)
{
var result = reader.Get(param);
return result;
}
}
public class ReportService_2 : BaseReportService_2<DataReader_2, ReaderParamModel>
{
// input is concrete class, reader.Get result is concrete class
protected override IReadResultModel Test(ReaderParamModel param)
{
var result = reader.Get(param);
return result;
}
}
// Third variant - fully parameterized
public class DataReader_3 : IDataReader<ReaderParamModel, ReadResultModel>
{
public ReadResultModel Get(ReaderParamModel param) { return null; }
}
public abstract class BaseReportService_3<TReader, TReaderParam, TReadResult>
where TReader : IDataReader<TReaderParam, TReadResult>
where TReaderParam : IReadParamModel
where TReadResult : IReadResultModel
{
protected TReader reader;
// input is concrete class, reader.Get result is concrete class
protected virtual TReadResult Test(TReaderParam param)
{
var result = reader.Get(param);
return result;
}
}
public class ReportService_3 : BaseReportService_3<DataReader_3, ReaderParamModel, ReadResultModel>
{
// input is concrete class, reader.Get result is concrete class
protected override ReadResultModel Test(ReaderParamModel param)
{
var result = reader.Get(param);
return result;
}
}
If you need the concrete types for input and output (like in the 3rd example), you should check, if you really need to specify the reader type for the ReportService.
// Fourth variant - decoupled
// the reader is not really needed for this example...
public class DataReader_4 : IDataReader<ReaderParamModel, ReadResultModel>
{
public ReadResultModel Get(ReaderParamModel param) { return null; }
}
public abstract class BaseReportService_4<TReaderParam, TReadResult>
where TReaderParam : IReadParamModel
where TReadResult : IReadResultModel
{
// reader is interface, can be assigned from DataReader_4 or different implementations
protected IDataReader<TReaderParam, TReadResult> reader;
// input is concrete class, reader.Get result is concrete class
protected virtual TReadResult Test(TReaderParam param)
{
var result = reader.Get(param);
return result;
}
}
public class ReportService_4 : BaseReportService_4<ReaderParamModel, ReadResultModel>
{
// input is concrete class, reader.Get result is concrete class
protected override ReadResultModel Test(ReaderParamModel param)
{
var result = reader.Get(param);
return result;
}
}

Pass Item as Derived Type from list of Base Type

I have a two tier object hierarchy like so:
public class BaseStat
{
}
public class IndividualDefensiveStat: BaseStat
{
} //and many other stats that inherit from BaseStat
I then have a Generic Repository like so:
public class StatRepository<TDerived> where TDerived: BaseStat
{
//ctr here
public TDerived FindById(int? id)
{
if(!id.HasValue)
throw new Exception("id has to have a value");
var result = _context.Set<TDerived>().Find(id);
return result;
}
public void Insert(TDerived item)
{
_context.Set<TDerived>().Add(item);
_context.SaveChanges();
}
}
Finally I have a service class that accepts a data context, and does CRUD operations based on the derived type passed in:
public class StatDataService
{
private IStatContext _context;
public StatDataService(IStatContext context)
{
_context = context;
}
public void InsertData<TEntity>(TEntity item) where TEntity : BaseStat
{
var repo = getRepository<TEntity>();
repo.Insert(item);
}
public TEntity GetById<TEntity>(int? id) where TEntity : BaseStat
{
return getRepository<TEntity>().FindById(id);
}
private StatRepository<TEntity> getRepository<TEntity>() where TEntity: BaseStat
{
return new StatRepository<TEntity>(_context);
}
}
I would like to have a list of BaseStat that houses items that derive from it. However, if I do a foreach loop and pass each item into the the Service's Insert method, TEntity/TDerived in this case is BaseStat.
How can I have TEntity/TDerived actually be the DerivedType that I am trying to target?

new at lambda as parameters

I'm new at this, can someone show me how this works and what goes in "mycode" in order to call the repository?
public class MemberService : ServiceBase<IMemberModel>, IMemberService
{
public MemberViewModel GetSingle(Expression<Func<MemberViewModel, bool>> whereCondition)
{
mycode
}
}
public abstract class RepositoryBase<T> : IRepository<T>
{
public T GetSingle(Expression<Func<T, bool>> whereCondition)
{
return ObjectSet.Where(whereCondition).FirstOrDefault();
}
}
Thanks!
What you need is probably a lambda based on a Member, not a MemberViewModel. Your method should probably be something like:
public MemberViewModel GetSingle( Expression<Func<Member,bool>> whereCondition )
{
var member = this.MemberRepository.GetSingle( whereCondition );
if (member != null)
{
return new MemberViewModel( member );
// or however you map from member to its view model
}
return null;
}

Categories

Resources