Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How restrict attribute on interface's method

Tags:

c#

I'd like to create a custom attribute but restrict its usage to interface's methods. Is it possible to do that in C#?

I'd like to have compilator error when I try to do this:

public class SomeClass
{
   [MyAttribute]
   public void SomeMethod() { ... }
}

[MyAttribute]
public interface IMyInterface { ... }

I want to be be able to do only this:

public interface IMyInterface
{
   [MyAttribute]
   void SomeMethod();
}

I can limit my attribute to interface or to methods but not both in the same time

[AttributeUsage(AttributeTargets.Method)]
like image 207
JiBéDoublevé Avatar asked Aug 01 '26 10:08

JiBéDoublevé


1 Answers

It's not possible. Have a look at the AttributeTargets enum. You can limit it to a method, but not for a method of an interface.

like image 194
Connell Avatar answered Aug 03 '26 22:08

Connell