user1047100
user1047100

Reputation:

Attributes in method override

I have a base class with a method. Derived classes just need to decorate that method with an attribute (different for each derived class) and leave the body untouched.

I did something like

Base class

public virtual int Method1()
{
    // body
}

public virtual int Method2()
{
    // body
}

Derived class A

[AttributeA(ParameterName = "AName", CommandName = "ACommand")]
public override int Method1()
{
    return base.Method1();
}

[AttributeA(ParameterName = "AnotherName", CommandName = "AnotherCommand")]
public override int Method2()
{
    return base.Method2();
}

Derived class B

[AttributeB(ParameterName = "BName", CommandName = "BCommand")]
public override int Method1()
{
    return base.Method1();
}

[AttributeB(ParameterName = "BnotherName", CommandName = "BnotherCommand")]
public override int Method2()
{
    return base.Method2();
}

and it works but it doesn't seem really pretty to me, the main reason being that it leaves the client free to override the body of the method, which is something I'd rather avoid, and it's also tedious to just repeat return base.Method();.

Is there a cleaner approach to solve this kind of problem? Am I missing something obvious?

Upvotes: 1

Views: 1587

Answers (2)

joe
joe

Reputation: 8654

Then you should call the method indirect.
Make a wrapper method that does all base code that should not be overridden:

private int MethodInternal() {

    // do common stuff here
    // original body of Method()

    return Method();
}

The body of Method() in the base class is empty, it's just there for the possibility to inject code.

This makes the call of return base.Method() in derieved classes unnecessary.

Example:

Base class

public virtual int Method()
{
    // empty
}

Derived class A

[AttributeA]
public override int Method()
{
    // no return base.Method() required
    return ???
}

Upvotes: 0

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

There's no other way to do that.

About...

"it's also tedious to just repeat return base.Method();[...]"

...I would say that Visual Studio auto-generates this code for you meaning that it's worth the effort (overriding to apply new attributes).

In fact, it's a core design decision in .NET languages since reflection on attributes provides the method Type.GetCustomAttributes(...) and it has an overload which accepts an input parameter called inherit and see its description:

inherit Type: System.Boolean

true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events [...]

Anyway, I don't find it an unclear way of doing that, since attributes are an implementation detail and this is why you require polymorphism to decorate an inherited member.

Maybe you're looking for something like this (I've invented new C# syntax!):

[AttributeA]
public metadataoverride int MethodA();

Upvotes: 1

Related Questions