russ
russ

Reputation: 81

C# interface question

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

Answers (5)

chilltemp
chilltemp

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

hunter
hunter

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

Jerod Houghtelling
Jerod Houghtelling

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:

  1. Create a small program that through the commandline will take in a file path to an assembly.
  2. Make the program load the assembly from the command line
  3. Get all types out of the assembly
  4. Verify that all of the types that implement your interface have the attributes set
  5. Have the program throw an exception if conditions are not met otherwise it runs successfully
  6. Add the program to the post-build event commands through the project properties

Note: This could also be done as a 'unit' test.

Upvotes: 1

Shahor
Shahor

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

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

There is no compile time way to enforce that.

Upvotes: 3

Related Questions