C# Error CS1618 – Cannot create delegate with ‘{0}’ because it or a method it overrides has a Conditional attribute

C# Error

CS1618 – Cannot create delegate with ‘{0}’ because it or a method it overrides has a Conditional attribute

Reason for the Error & Solution

Cannot create delegate with ‘method’ because it has a Conditional attribute

You cannot create a delegate with a conditional method because the method might not exist in some builds.

The following sample generates CS1618:

// CS1618.cs  
using System;  
using System.Diagnostics;  
  
delegate void del();  
  
class MakeAnError {  
   public static void Main() {  
      del d = new del(ConditionalMethod);   // CS1618  
      // Invalid because on builds where DEBUG is not set,
      // there will be no "ConditionalMethod".  
   }  
   // To fix the error, remove the next line:  
   [Conditional("DEBUG")]  
   public static void ConditionalMethod()
   {  
      Console.WriteLine("Do something only in debug");  
   }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...