locked
How defines a constraint on class type if It has a custom attribute? RRS feed

  • Question

  • Hi,

    there is any way to force a class to implement an interface , if It has an specific custom attribute?

    I want to have a compile time error , if the class with specific attribute does not implement an specific interface.

    thanks,

    [myAttrib]
    public MyClass:IMyInterface
    {
    
    }
    If myClass is not typeof(IMyInterface) , I will get an error in compile time.
    Sunday, May 8, 2011 9:13 AM

Answers

  • I think you will need some kind of pre-build or post build event that scans all the classes and ensures that they implement a certain interface. I think the only way to do this pre-build is with NRefactory. A post-build event would be easier because your code has compiled and you can just use reflection, get all types from your DLL and see which ones have the attribute, and then ask what interfaces they implement and return a non-zero integer from a console application if so. Then use that console application as a post-build event.

    Monday, May 9, 2011 2:10 AM
  • Hello,

    Another way of doing that is using StyleCop, you can then write a custom rule and throw an error.


    Eyal (http://shilony.net), Regards.

    Any fool can write code that a computer can understand. Good programmers write code that humans can understand. -- Martin Fowler.
    Monday, May 9, 2011 2:54 AM

All replies

  • I think you will need some kind of pre-build or post build event that scans all the classes and ensures that they implement a certain interface. I think the only way to do this pre-build is with NRefactory. A post-build event would be easier because your code has compiled and you can just use reflection, get all types from your DLL and see which ones have the attribute, and then ask what interfaces they implement and return a non-zero integer from a console application if so. Then use that console application as a post-build event.

    Monday, May 9, 2011 2:10 AM
  • Hello,

    Another way of doing that is using StyleCop, you can then write a custom rule and throw an error.


    Eyal (http://shilony.net), Regards.

    Any fool can write code that a computer can understand. Good programmers write code that humans can understand. -- Martin Fowler.
    Monday, May 9, 2011 2:54 AM
  • And what forces anyone to add that attribute to the class? How would that kind of attribute be useful?
    Monday, May 9, 2011 5:40 PM