Thursday, March 22, 2012

Disabling Compiler Warnings

In this post we will look for a technique which allow us to disable compiler warnings in a particular code region.
Considering the following code :


public string Hello(string Input)
{
            switch (Input)
            {
                case "hell":
                    return "a";
                    break; //Compiler generates warning -> Unreachable Code Detected
                case "Wow":
                    return "a";
                    break;//Compiler generates warning -> Unreachable Code Detected
                default:
                    return "a";
                    break;//Compiler generates warning -> Unreachable Code Detected
                }
}
For the time being consider the code to be sensible and I want to go with it. 
Now if I wish to get rid of compiler warnings without making it sensible to compiler following lines need to be appended in the above mentioned code.



public string Hello(string Input)
{
            #pragma warning disable
            switch (Input)
            {
                case "hell":
                    return "a";
                    break; //Compiler generates warning -> Unreachable Code Detected
                case "Wow":
                    return "a";
                    break;//Compiler generates warning -> Unreachable Code Detected
                default:
                    return "a";
                    break;//Compiler generates warning -> Unreachable Code Detected
                }
               #pragma warning restore
}

The #pragma a preprocessor command restricts compiler to generate warning under the defined region.If you expect a certain warning to occur, and don't want to fix it, the #pragma directives shown here are useful.


1 comment: