In C#, is it possible to write something like this:
public class MyClass<T> : T
where T : class, new()
{
}
I know that the above implementation does not compile, but what I am actually trying to achive is implementing some kind of generic wrapper to an unknown type, so that an client can call the wrapper just as he would call the type, provided by the parameter T, instead of calling it using something like wrapper.Instance.SomeMember().
Thanks in advance!
This isn’t possible.
In my opinion, I don’t think that a wrapper should be implemented using inheritance.
For example, let’s say we’ve an
Engineclass and you need to implement aFerrariEngine. And you have aCarclass.You’re saying that
Carshould inheritFerrariEngine. It looks terrible for me!At the end of the day, you’re looking to do something like dependency injection using inheritance and, again, this isn’t the right path.
My suggestion is don’t try to make your life easier: decide an architecture based on rational points.
UPDATE
The OP said in some comment:
You don’t need to make strange things to get what you want:
Finally, if we create an instance of
FerrariCar:The engine will be instantiated and started, without developer intervention!
Check how
Lazy<T>and basic generic constraints make the job 😉In summary:
Lazy<T>the engine will be instantiated only when some access theEngineproperty.FerrariEngineimplements a parameterless constructor callingStart()itself, it will start the engine.I believe that this sample illustrates you how you can get what you’re looking for and using C# “as is”!