Zammy (4) [Avatar] Offline
#1
I want to say first that your book is great! I though I knew c#2 but it actually was not right. I had no idea about where keyword for example.

It is very powerful concept, kinda like contracts, but the first time I try to use it I hit an obstacle.

I want to validate that T is of base interface. The base interface has nothing in it, its there just for validation. But because they are interfaces not classes it did not work.
So I change the IBaseInterface to BaseClass of all my entities. Idea that it needs to be of a base class at least (the instance I am sending as T). But It did not work also saying it cannot convert them implicitly. Anyidea how I can enforce for T to be of just certain Interfaces?

class PhysicalSystem : IUpdate,ISystemService<IPhysicalEntity>
{
List<IPhysicalEntity> physicalObjects = new List<IPhysicalEntity>();

#region IUpdate Members

public UpdateFrequency Update(UpdateState state)
{
throw new System.NotImplementedException();
}

#endregion

#region ISystemService<IPhysicalEntity> Members

public void AddEntity(IPhysicalEntity entity)
{
throw new System.NotImplementedException();
}

#endregion
}

interface ISystemService<T> where T : IBaseInterface
{
void AddEntity(T entity);
}

interface IPhysicalEntity : IBaseInterface
{}


Message was edited by:
Zammy
jon.skeet (451) [Avatar] Offline
#2
Re: type constraining in generics
I'm not sure which bit isn't working for you. You can certainly specify interfaces instead of classes in the constraints.

The code you've given basically compiles, when the relevant interfaces/types are added - where are you getting a conversion issue?

Jon
Zammy (4) [Avatar] Offline
#3
Re: type constraining in generics
The problem comes that I want to enforce that an object implements a base interface or its subtype interfaces. There is no covariance I think you call it in the book.

I can say that an object implements certain interface or its base class is certain class. I cannot say, "implement an interface or the interfaces derived from it"

Maybe I am missing something but It did not work with me.
jon.skeet (451) [Avatar] Offline
#4
Re: type constraining in generics
If the type implements an interface derived from it, then it already implements the interface - e.g. if I have IFoo and IBar : IFoo, then just putting the constraint "T : IFoo" will include things implementing IBar.
Zammy (4) [Avatar] Offline
#5
Re: type constraining in generics
It did not work! I tried exactlly that. I wonder why it had problem with it.
Anyway its dead gone code. Thank you very much for the help.
jon.skeet (451) [Avatar] Offline
#6
Re: type constraining in generics
No problem. If you ever get back the code which didn't work, let me know. It really should have been okay...