I can’t figure out why the following wont work, any ideas??
public interface IFieldSimpleItem { } public interface IFieldNormalItem : IFieldSimpleItem { } public class Person { public virtual T Create<T>() where T : IFieldSimpleItem { return default(T); } } public class Bose : Person { public override T Create<T>() where T : IFieldNormalItem //This is where the error is { return default(T); } }
The reason why I am doing this is due to the fact that if a developer inherits from Bose, Bose relies on the instance being creating being at least of IFieldNormalItem. Whereas the below only relies on it being IFieldSimpleItem but the above should force it to be at least IFieldNormalItem.
public class Person { public virtual IFieldSimpleItem Create() { return null; } } public class Bose : Person { public override IFieldSimpleItem Create() { return null; } }
Cheers Anthony
I’m pretty sure you’re out of luck as far as using the compiler and generics to save you some runtime checks. You can’t override something that doesn’t already exist, and you can’t have different return types to the same methods.
I can’t say I completely understand your motivation, but it has technical merit.
My first attempt was using the base class having a Non-Virtual public interface, and then having another protected virtual method
CheckCreatedTypethat would allow anything in the chain to inspect the type before the base class Create was called.The following sticks in runtime checking at the base class. The unresolvable issue is you still have to rely on the base class method being called. A misbehaving subclass can break all checks by not calling
base.CheckCreatedType(item).The alternatives are you hardcode all the checks for all subclasses inside the base class (bad), or otherwise externalize the checking.
Attempt 2: (Sub)Classes register the checks they need.
The check is done by the subclass registering a delegate to invoke in base class, but without the base class knowing all the rules upfront. Notice too that it’s still the Non-Virtual public interface which allows the base class to check the results before returning them.
I’m assuming that it’s a developer error that you’re trying to catch. If it’s applicable, you can adorn the runtime check method with
System.Diagnostics.Conditional('DEBUG')], allowing the Release version to skip the checks.My knowledge of generics isn’t perfect, so maybe this is unnecessary. However the checks here don’t have to be for type alone: this could be adapted for other uses. e.g. the delegate passed in
Register..doesn’t have to just check the reference is a specific type’* Note that it’s probably not good to create the dictionary on the type name as written above; this working is a little simplistic in order to illustrate the mechanism used.