Reputation: 1562
is there a keyword for the question "?" mark below or a way to achieve the same effect without using templates?
abstract class A
{
public abstract void Attach(? x);
}
class B : A
{
public override void Attach(B b) {}
}
class C : A
{
public override void Attach(C c) {}
}
so that:
var b1 = new B();
var b2 = new B();
var c = new C();
b1.Attach(b2);
b1.Attach(c); // should not compile
EDIT:
with templates i mean type parameters such as Attach<T>(T x, T y)
// if we ignore that the example takes 1 argument
Upvotes: 1
Views: 59
Reputation: 42320
Annoyingly, no. The closest you can get is:
abstract class A<T> where T : A<T>
{
public abstract void Attach(T x);
}
class B : A<B>
{
public override void Attach(B b) { }
}
class C : A<C>
{
public override void Attach(C c) { }
}
This doesn't however stop someone from writing:
class D : A<B>
{
...
}
If you want to avoid this, you need a runtime check for this.GetType() == typeof(T)
or similar in A
's constructor.
Upvotes: 3
Reputation: 1632
You can make A Generic
like so:
abstract class A<T> where T : A<T>
{
public abstract void Attach(T x);
}
class B : A<B>
{
public override void Attach(B b) {}
}
class C : A<C>
{
public override void Attach(C c) {}
}
Than the following does not comile
b1.Attach(c); // should not compile
Upvotes: 2