Here is an interesting problem that I just ran into. You can do what I want using extension methods, but it is not possible to do with members of the class itself.
Using extension methods, you can write a method that has a signature that looks like this:
public static void DoStuff<T>(this T arg1, T arg2)
this ensures that both arguments are of any type that you need. This becomes more useful when used with delegates.
public static void DoStuff<T>(this T arg1, Action<T> arg2)
However, I cannot get this to work with members. There is no such limitation as this:
public void DoStuff<T>(T arg1) where T : typeof(this)
If this worked, then you can define a method in your base class like this (I used streams as they are built into the hierarchy in .NET):
class Stream { public void DoStuff<T>(T stream) where T : this { } }
and then in a subclass it would be impossible to call it this way:
ByteStream bs = new ByteStream() bs.DoStuff(new Stream())
Is there any way to do this? I believe it automatically infers types from arguments, and extension methods are syntactic sugar. This is probably why this works; because extension methods are replaced with static calls, which then allow type inference.
I ask because I am trying to move the extension method to a common base class and cannot compile it without adding type information.
To clarify. This is not a case of adding where T : MyType , because if I create a type called MySubType that inherits from MyType , I can call DoStuff on the MySubType instance and pass a MyType as an argument. This also means that in the case when it takes an Action<T> , I will not be able to call MySubType methods without MySubType in the first place.