I'm studying C#, but I'm used to programming in PHP.
I know that in PHP it is possible to suppress some error messages by putting the
@ (at) at the beginning of the expression.
For example, if I wanted the variable
$a not to issue the
Erro Notice because it doesn't exist, I could simply use an
echo $a; // Notice: undefined variable 'a' echo @$a;// Sem erros
Of course it's not one of the best practices, but actually I'm not here to find out what's good practice and what isn't, but I want to learn C# and I want to learn everything!
Is there an error message suppression mechanism in C# the same way as in PHP?
Yes there is, it is the
#pragma warning . Some considerations must be made.
This only exists at compile time as this is a compile directive. Nothing will change when running the code.
C# has the philosophy of relatively few warnings (now it's increased a bit), bug or run without restrictions is preferred. The language was designed for this.
Its use must be extremely rare. Most codes will never have this.
It's useful when you're doing something normally weird that might actually be a problem and there's no other way to solve it via code. That is, you really know that you have no problem in that situation and you need to inform the compiler about it. A warning is not an error, the compiler knows that the programmer can be right in rare circumstances.
Nobody puts this out of the blue, in general one realizes that it is necessary after seeing the code compiling and showing a specific warning . After a lot of thinking and making sure there is no other way, then you can specifically disable this warning through your code. So if one day another warning appears in a maintenance, it will be presented. Never disable all warnings (not specifying the warning(s) number(s) ).
Its effect is worth a block of code until it is turned off:
#pragma warning disable 168 //desabilitei aqui por causa de.... ... código ... #pragma warning restore
There is a recommendation to always comment why this is used. If you can't give a good reason, there's something wrong there. It's not worth blaming the compiler 🙂
There is also
#warning which is used for your code to generate a warning to the compiler. This should probably be used conditionally. Or something that should no longer be used (although there is another solution for this). Rare use, as every build directive should be.
It has several build directives that affect how the build works and has a side effect on the code.