Reputation: 81
If I want a bunch of classes to implement a method, I can just make them implement an interface. However, if I want the method to always be decorated with two custom attributes, if there a syntax for that? In other words, I want every class that implement method Run() to attach a descriptionAttribute and a versionAttribute.
Update: Is there a way to make classes that implement Run() generate a compile error if they did not attach the two attributes?
Upvotes: 7
Views: 366
Reputation: 8960
You could use an abstract class to validate the attributes when the class is initialized.
abstract class MustImpliment
{
protected MustImpliment()
{
object[] attributes = this.GetType().GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attributes == null || attributes.Length == 0)
throw new NotImplementedException("Pick a better exception");
}
// Must impliment DescriptionAttribute
public abstract void DoSomething();
}
class DidntImpliment : MustImpliment
{
public override void DoSomething()
{
// ...
}
}
Update: This will not cause a compiler error, but you can use this as part of a Unit Test as Jerod Houghtelling suggested.
Upvotes: 0
Reputation: 63552
public interface IRun
{
void Run();
}
public abstract class RunBase : IRun
{
[Description("Run Run Run")]
[Version("1.0")]
public abstract void Run();
}
public abstract class SoRunning : RunBase
{
public override void Run() {}
}
you should be able to get the Attributes off of the base class
Upvotes: 6
Reputation: 4867
I don't think there is built in compile time support. However one way you could get around this is to create a program or script that is ran at compile time by using the projects build events.
For example:
Note: This could also be done as a 'unit' test.
Upvotes: 1
Reputation: 415
Maybe you should consider using abstract classes ? http://msdn.microsoft.com/en-us/library/k535acbf%28VS.71%29.aspx
(Not sure I understood your question well)
Upvotes: 3