товіаѕ
товіаѕ

Reputation: 3244

c# override method with more specific type declaration

Is there a way to implement the following logic in C#? (note: the following code does not compile)

abstract class Foo {
    void Bar(Object obj);
}

class SubFoo<T> : Foo {
    override void Bar(T obj);
}

Notice how SubFoo overrides the Bar(..) method with a more specific parameter type.

Upvotes: 0

Views: 2032

Answers (2)

Nick
Nick

Reputation: 4766

No, you cannot do that. Imagine this code:

Foo myFoo = new SubFoo<string>();

myFoo is is a Foo which takes an object, but it is actually an implementation of SubFoo which takes a string. So what would you expect to happen when you call

myFoo.Bar(1);

Foo.Bar takes an object, so you can pass in an integer, but SubFoo expects a string not an integer. The world blows up.

Upvotes: 2

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

No you can't the override must have the same signature as the original. There are several alternatives:

Make the base class generic

abstract class Foo<TArg>
{
    public abstract void Bar(TArg obj);
}

class SubFoo<T> : Foo<T>
{
    public override void Bar(T obj) { }
}

Leave the original function and add an overload

abstract class Foo
{
    public abstract void Bar(object obj);
}

class SubFoo<T> : Foo
{
    public void Bar(T obj) { }
    public override void Bar(object obj) => this.Bar((T)obj);
}

Use an interface instead of an abstract class to hide the less specific overload

interface Foo
{
    void Bar(object obj);
}

class SubFoo<T> : Foo
{
    public void Bar(T obj) { }

    void Foo.Bar(object obj) => this.Bar((T)obj);
} 

Upvotes: 7

Related Questions