Pierre-Luc
Pierre-Luc

Reputation: 160

Conditional method depending on class attribute

I'm wondering if a conditional method can have his condition on a class attribute.

For instance :

class Class1 
{
   public bool _doStuff;

   [Conditional(_doStuff)]
   public static void Stuff() {
      // Do the stuff
   }
}

Like the [Conditonal("DEBUG")].

Does anyone know about this?

Upvotes: 0

Views: 445

Answers (3)

Roman Ambinder
Roman Ambinder

Reputation: 369

No there isn't.

1.)You can do is post compile intercepting the generated IL and remove any unwanted generated IL code. Look at - https://msdn.microsoft.com/en-us/library/system.reflection.emit.ilgenerator%28v=vs.110%29.aspx

2.)Use preprocessing tags at class definition and every where you use the class.
For example :

#if test
    internal class SomeClass
    {
      public void SomeMethod(){}
    }
#endif

and :
public static void main()
{
#if test
      var someClass= new SomeClass();
      someClass.SomeMethod();
#endif

}

Upvotes: 0

Stefan
Stefan

Reputation: 17658

The input of the attribute ought to be a constant. It's used as input for the constructor, at build time.

So in this case it wouldn't work.

If you truly want something conditional, that can be set through variables, I would suggest writing your own attribute class.

Upvotes: 2

i3arnon
i3arnon

Reputation: 116538

This doesn't exist. More to the point, it's illogical.

A method marked as Conditional doesn't take part in the build process if the condition isn't met. This decision can't be made in runtime.

The code is omitted as if it was never written and the executable (or dll) doesn't contain that method.

Upvotes: 10

Related Questions