1

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.

[myAttrib]
public MyClass:IMyInterface
{

}

If myClass is not typeof(IMyInterface) , I will get an error in compile time.

thanks,

hm1984ir
  • 554
  • 3
  • 7
  • You could create an abstract class driving from the interface and get your final class drive from that abstract class. – FIre Panda May 08 '11 at 09:35

1 Answers1

0

In case of properties, You could create an abstract class inheriting the interface and gets your final class drive from that abstract class.

Have a look at

public interface Test
    {
        string Name { get; set; }
    }

    public abstract class Test1 : Test
    {
        public abstract string Name { get; set; }
    }

    public class Test2 : Test1
    {

    }

For custom attribute you could do

public class Alias : System.Attribute
    {
    string[] _types;

    public Alias(params string[] types)
    {
        this.Types = types;
    }
    public Alias()
    {
        this.Types = null;
    }

    public string[] Types
    {
        get { return _types; }
        set { _types = value; }
    }
  }

    public interface Test
    {
        Alias Attrib{ get;}
    }

    public abstract class Test1 : Test
    {
        public abstract Alias Attrib { get; }
    }

    public class Test2 : Test1
    {

    }

Hope I answer your question.

FIre Panda
  • 6,537
  • 2
  • 25
  • 38
  • Hi Abdul,thanks for you reply But It's seems you didn't get my question well I said [custom attribute] not property – hm1984ir May 08 '11 at 10:09