1

I would like to control in a class the signature of certain methods so that it throws a compilation error if a method does not have the signature I want.

I have thought do it creating a custom attribute, something like this:

public class CustomAttributeForMethodWithStringParameterFirstAttribute : Attribute
{
}

public class MyClass
{
   [CustomAttributeForMethodWithStringParameterFirst]
   public void Method1 (string p)
   {
   }

   [CustomAttributeForMethodWithStringParameterFirst]
   public void Method2 ()  // <--- I wish a compile error
   {
   }
}

But... Now I do not know how to continue. Is it possible do this via attributes?

Thanks in advance. If not, is there any way to do it?

EDIT Sorry, I have simplified my scenario to expone the concrete problem. I'm writting the interface for a WCF service and I wish implement this attributes in the interface. Certain methods must have one string parameters in first position for custom operations. I've developed a custom attribute to do something with this first parameter before methods calls of my service.

public interface MyInterface
{
   [CustomAttributeForMethodWithStringParameterFirst]
   void Method1 (string p);

   [CustomAttributeForMethodWithStringParameterFirst]
   void Method2 ();  // <--- I wish a compile error
}
Rafael León
  • 71
  • 1
  • 9
  • Why not create an abstract base class with those methods? – Ron Beyer Apr 10 '18 at 14:41
  • 3
    This seems like you need an [interface](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/index). If that's not what you need, can you give us a little more information as to why you are trying to do this? – Lews Therin Apr 10 '18 at 14:41
  • 1
    You want the class to have methods with certain signature, which implies one-to-one that you need an interface. If not, this may very well be an X-Y problem. – Sнаđошƒаӽ Apr 10 '18 at 14:44
  • I edit the post to explain my scenario – Rafael León Apr 10 '18 at 15:11
  • Unfortunately this isn't possible using Attributes. There are one or two attributes that generate compiler warnings (like `ObsoleteAttribute`) but they are "baked into" the compiler to look for those. You can build a Rosyln code-analyzer though: See this question: https://stackoverflow.com/questions/154109/custom-compiler-warnings – Ron Beyer Apr 10 '18 at 16:02
  • I think it's possible with some IL weavers (such as PostSharp), however I hope you can find a better solution for your problem. – Evk Apr 10 '18 at 18:46

0 Answers0