How to make the using statement take effect only in debug?

Viewed 77

I want to implement the following c++ code in c#, I want it to work only in Debug

public class Test
    {
        ~Test()
        {
            //code
        }
    }
#if DEBUG
 #define TEST_DEBUG Test test;
#else
 #define TEST_DEBUG
#endif

void Func()
{
  TEST_DEBUG
  //code
}

I try to implement it using the using statement in c#.

I have a Test class which implements the IDisposable . The GetTest function return null directly in release, but the c# compiler is not optimized it.

It's there any to implement it?

Here is sample code:

  [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Test GetTest()
        {
#if DEBUG
            return new Test();
#else
            return null;
#endif
        }

        private static void Main(string[] args)
        {
            {
                using var test = GetTest();
                Console.WriteLine("test");
            }
        }

        public class Test : IDisposable
        {
            public void Dispose()
            {
            }
        }

code in ildasm(release version)

 .maxstack  1
  .locals init ([0] class ConsoleApp2.Program/Test test)
  IL_0000:  call       class ConsoleApp2.Program/Test ConsoleApp2.Program::GetTest()
  IL_0005:  stloc.0
  .try
  {
    IL_0006:  ldstr      "test"
    IL_000b:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_0010:  leave.s    IL_001c
  }  // end .try
  finally
  {
    IL_0012:  ldloc.0
    IL_0013:  brfalse.s  IL_001b
    IL_0015:  ldloc.0
    IL_0016:  callvirt   instance void [mscorlib]System.IDisposable::Dispose()
    IL_001b:  endfinally
  }  // end handler
  IL_001c:  ret
} // end of method Program::Main

Supplement: I try to used Action,but it's more slowly then using statement.

public static Test(Action action)
{
#if DEBUG
    using var test = new Test();
#endif

    action();
}

public static void Main(string[] args)
{
    Test(() => Console.WriteLine("test"));
}
1 Answers

The using statement needs to be wrapped in a #if DEBUG block

public static void Main(string[] args)
{
#if DEBUG
    using var test = new Test();
#endif

    Console.WriteLine("test");
}

You haven't stated, but I assume you're trying to avoid repeating yourself everywhere. It's possible to pass the code being tested as a parameter:

public static Test(Action action)
{
#if DEBUG
    using var test = new Test();
#endif

    action();
}

public static void Main(string[] args)
{
    Test(() => Console.WriteLine("test"));
}
Related