Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional attribute on a virtual function

Tags:

c#

I'm wondering why when you put a System.Diagnostics.Conditional("DEBUG") attribute on the a virtual method in a base class that you don't get compiler errors on derived classes that override that same virtual method but don't have the conditional attribute when the condition isn't met. Example:

public class MyBaseClass  
{  
    [System.Diagnostics.Conditional("DEBUG")]  
    public virtual void Test()  
    {
        //Do something  
    }  
}  

public class MyDerivedClass : MyBaseClass
{
    public override void Test()
    {
        //Do something different
    }
}

It seems that when DEBUG is not defined, the conditional would essentially make a sitation where the override method can't exist because there is no virtual function in the actual IL output. Yet in my testing, the compiler seems to generate the code just fine either way. Does the conditional just throw out the IL for the function body but not make any real changes to the class signature?

like image 616
Jeremiah Gowdy Avatar asked Jan 14 '10 19:01

Jeremiah Gowdy


1 Answers

I think this is because the attribute only indicates the method as not being callable by ignoring calls to that method, but the method does exist.

Edit: I went ahead and experimented a bit with this and if you inspect a release build of the following code in Reflector, you'd notice the call to the Test method being absent.

 public class TestClass
    {
        [ConditionalAttribute("DEBUG")]
        public static void Test()
        {
            Console.WriteLine("Blierpie");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting test");
            TestClass.Test();
            Console.WriteLine("Finished test");
            Console.ReadKey();
        }
    }
like image 72
Anton Avatar answered Sep 30 '22 08:09

Anton