Here's an interesting problem that I have just come across. It is possible to do what I want using extension methods, but does not seem possible to do with members of the class itself.
With extension Methods it is possible to write a method that has a signature that looks like this:
public static void DoStuff<T>(this T arg1, T arg2)
this enforces that both arguments are of whatever type you care calling it on. 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 constraint as this:
public void DoStuff<T>(T arg1) where T : typeof(this)
if this did work then you could define a method on your base class like this (I've used streams as they are a built in hierarchy in .NET):
class Stream
{
public void DoStuff<T>(T stream) where T : this
{
}
}
and then on a subclass it would not be possible to call it like this:
ByteStream bs = new ByteStream()
bs.DoStuff(new Stream()) // Error! DoStuff() should be inferred as DoStuff<ByteStream>()
Is there any way of doing this? I believe that automatically inferring the types from the arguments, and extension methods are syntactic sugar. And that is probably why it works; because the extension methods are replaced by static calls, which then allow the type to be inferred.
I ask because I am trying to move an extension method into a common base class, and cannot get it to compile without adding the type information.
To clarify. This isn't a case of just adding where T : MyType
because if i create a type called MySubType
that inherits from MyType
I will be able to call DoStuff
on an instance of MySubType
and pass a MyType
as the parameter. This also means that in the case where it takes an Action<T>
I will be unable to call methods of MySubType
without casting first.