Is there a way in code to disable certain warnings in C# alike #pragma warning(cmd: warningsNo) in c++?
Almost precisely the same directive.
Yes. See the docs for the complete reference.
To disable a warning you can use #pragma. For example, add the following line just before the code in question:
#pragma warning disable RCS1194
The preceding example disables the warning RCS1194 which is "Implement exception constructors."
To enable the warning again, add the following after the code in question:
#pragma warning restore RCS1194
If you have more than one warning, use a comma separated list. For example:
#pragma warning disable RCS1021, RCS1102, RCS1194
Although the documentation states that the prefix CS is optional, the prefix RCS is not optional. I believe this also applies for other prefixes. My recommendation would be to always use the prefix to be on the safe side.
Related
I've the following snippet of code in one of my C# classes:
public override int GetHashCode()
{
// Thanks: https://stackoverflow.com/a/5910237
if (set == null) return 0;
int h = 0x14345843;
foreach (T elem in set)
{
h = unchecked(h + set.Comparer.GetHashCode(elem));
}
return h;
}
With this code, I'll receive a warning: "Non-readonly field referenced in 'GetHashCode()'".
As that is intended in this case, I added the following pragma to dismiss that warning: #pragma warning disable RECS0025.
However, after adding that pragma, I received a new warning only in the Unity Editor - not when building the code in Visual Studio:
warning CS1692: Invalid number
Double-clicking it would take me straight to that #pragma warning disable RECS0025 line.
What am I doing wrong here? The goal is to suppress the RECS0025 warning, of course without causing another warning.
Extra: I tried disabling the CS1692 warning around the RECS0025 pragmas, but that didn't work either; the CS1692 error continued occurring.
Extra extra: I've some code elsewhere as follows:
#pragma warning disable RECS0108
static SharedPool<Tuple<HierarchyMember, string>, ReactiveProperty<T>> _sharedPool;
#pragma warning restore RECS0108
This does not cause the CS1692 error to occur. That is, if I remove the #pragma warning disable RECS0025 from around the GetHashCode function, but leave the above RECS0108 pragma in, there will be no CS1692 warning.
Not sure how this adds up with the two provided answers.
That's due to the non-numeric prefix. I'm guessing Unity is using an old compiler or not the most recent spec of C#? I'm not familiar with the Unity compiler at all, but this should fix it.
Be aware this disables all warnings, so I'd limit it in scope as much as possible.
public override int GetHashCode()
{
// Thanks: https://stackoverflow.com/a/5910237
#pragma warning disable
if (set == null) return 0;
int h = 0x14345843;
foreach (T elem in set)
{
h = unchecked(h + set.Comparer.GetHashCode(elem));
}
return h;
#pragma warning restore
}
Before C# 6, you aren't allowed to use prefixes on pragma instructions - everything is assumed to be intended for the C# compiler.
So to take your C# example:
#pragma warning CS1692
and
#pragma warning 1692
are equivalent, but the first one is not valid until C# 6. Unfortunately, Unity uses an older compiler. There is no way of specifying RECS0025 in source code without that. Options:
fix the error - presumably by calculating the hashcode at construction and asserting that the set contents cannot ever change (it should be a read-only set
anyway to be used in this way)
ignore the error visually
find another way to suppress that warning
disable the tool that is raising the warning
I'd go with the first one.
Back in the days of C/C++, Microsoft had a #define, which allowed programmers to reference an unused parameter. The declaration, part of windef.h, is:
#define UNREFERENCED_PARAMETER(P) {(P)=(P);}
#define UNREFERENCED_LOCAL_VARIABLE(L) {(L)=(L);}
Whatever the exact name and syntax, the line had the effect of
Telling the compiler to not flag this unused parameter as a warning
The later stages of the compiler was smart enough to not include the line in the binary (or so I recall)
Visually tells the viewer that the unreferenced parameter was not an oversight.
Is there a similar syntax in C#?
Although it makes no difference for this question, but the DevExpress CodeRush Visual Studio add-in flags all unused parameters, even in event handlers, as a warning.
NOTE:
As I stated in my comment, I do not want to use pragma blocks. The purpose is to add a line of code that references the parameter for warning sake but adds none to trivial overhead, like what the windef.h header file macro did.
Maybe the discard _ is what you're looking for:
void Foo(string parameter)
{
_ = parameter;
}
Using the SuppressMessage attribute you can suppress warnings where ever you want:
[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "fileIdentifier")]
static void FileNode(string name, bool isChecked)
{
string fileIdentifier = name;
string fileName = name;
string version = String.Empty;
}
This also gives the reader an explicit understanding that this is intended behavior.
More on the SuppressMessage attribute.
You can use the following syntax to disable and re-enable specific warnings. Surround the code that declares the unused/unreferenced paramter:
#pragma warning disable <warning-number>
// ... code that declares the unused parameter
#pragma warning restore <warning-number>
Where the <warning-number> above would be the warning number issued by the compiler that you wish to suppress. Presumably that would be C# warning number 219.
Using pragma statements only allow turning on or turning off compiler warnings. Since it is most likely you only want to affect the file you are working in, this will cause problems if someone later decides to disable the warning project wide. Every file compiled after the file with the pragma restore in it may report an unwanted warning.
Embedded developers will recognize this as the common problem of trying to enable and disable interrupts without knowing what the previous interrupt status was.
Here's a hack that you might use:
namespace YourComapany.Tools{
class CS
{
public static void UNREFERENCED_PARAMETER<T>(T t) {if(t == null) {T d=t;}
}
};
...
CS.UNREFERENCED_PARAMETER(whatever);
I am using T4 to generate some code. The code will be in a class called "MyClass.generated.cs" and typical output will look like this.
//<autogenerated/>
namespace MyNamespace
{
using System;
using System.CodeDom.Compiler;
[GeneratedCode("T4", "1.0.0.0")]
public partial class MyClass: SomeBaseClass
{
private SomeBaseClass myBackingField;
}
}
However, even though the class is decorated with the GeneratedCodeAttribute, I still get a Code Analysis warning as follows:
Field 'MyNamespace.MyClass.myBackingField' is never assigned to, and will always have its default value null
I have ensure that the Project Properties → Code Analysis → "Suppress results from generated code (managed only)" checkbox is checked.
Please note that I understand the meaning of the warning - I just want to know how to suppress it :)
Possible solutions
I could modify my generator to use Suppressions to suppress specific warnings, but this is extra work that I shouldn't have to do (as generated code should be ignored by Code Analysis).
Related Questions
Visual studio code analysis for generated files
EDIT with background context
The actual generated code is essentially a wrapper around SomeBaseClass. There are 100+ types in a namespace, and I want to change the behaviour of a subset of those. There are other warnings being generated as well - I just used this one as an example. Consider for example, if there is a property SomeBaseClass.MyObsoleteProperty, which is decorated with the ObsoleteAttribute. My code generater would still create a MyClass.MyObsoleteProperty which would raise a Code Analysis warning.
Another example would be where the SomeBaseClass (which is from a 3rd-party) would itself raise Code Analysis warnings if they had bothered to check for them (maybe the class is not CLS-compliant, for example). My wrapper will recreate any errors they have (and that would actually be the desired behaviour).
I figured it out - this is not a Code Analysis warning - it's a compiler warning.
Therefore, the only way to disable it is to modify the generator to enclose the class in pragma directives to suppress compiler warnings, e.g
#pragma warning disable warning-list
// Now generate some code
#pragma warning restore warning-list
WARNING
Note that this is a dangerous feature - compiler warnings are there for a reason! Try and limit your use of it to as small a section as possible.
More information can be found at
Suppressing "is never used" and "is never assigned to" warnings in C#
List of compiler warnings and errors here.
I think you mean
#pragma warning disable
// generated code
#pragma warning restore
the "warning-list" is a placeholder in MSDN documentation for something like "c0605,c0403,c3498" etc
I want to raise warnings, if certain properties are used in the code. I could use the obsolete-attribute. But the used properties aren't obsolete, thus it wouldn't be that correct to give an obsolete warning.
How can I define own warnings for some properties that are printed during compilation, when the property is used?
Why not use the obsolete atrribute?
You can use task list with comments. Just use of the keywords defined here
Is there a way to suppress warnings in C# similar to Java's #SuppressWarnings annotation?
Failing that, is there another way to suppress warnings in Visual Studio?
Yes.
For disabling, use:
#pragma warning disable 0169, 0414, anyothernumber
Where the numbers are the identifiers of the warnings that you can read from compiler output.
To reenable the warnings after a particular part of code (which is a good idea) use:
#pragma warning restore 0169, anythingelse
This way you can make the compiler output clean, and keep yourself safe because the warnings will only be suppressed for that particular part of code (where you made sure you don't need to see them).
Yes there is you can use the pragma warning annotation like this:
#pragma warning disable 414
//some code that generates a warning
#pragma warning restore 414
omitting the numbers disables and restores all warning codes...
I highly recommend using the following form
#pragma warning disable 649 // Field 'field' is never assigned to, and will always have its default value 'value'
#pragma warning restore 649
The comment on the first line is taken from the first like of the MSDN documentation for Compiler Warning (level 4) CS0649. Since warnings are numbered in C#, this is your only reference to what's actually going on in the code when you see a warning disabled. Placing it at the end of the line is the only way to get the reason to show up in the search results window when you do a search in your whole solution for pragma warning.
You can identify the warning numbers by looking in the Output window after building your project. Make sure it says Show output from: Build.
There is. See the MSDN page on how to suppress compiler warnings.
From Visual Studio, go to your project properties, select the build tab, and enter the warning number in the Suppress Warnings field.
From code, to disable specific warnings, you can use the #pragma directive:
public class MyClass
{
#pragma warning disable 0168
// code
// optionally, restore warnings again
#pragma warning restore 0168
// more code
}
You could check #pragma directives: http://msdn.microsoft.com/en-us/library/441722ys(VS.80).aspx.
Have a look at the SuppressMessageAttribute in VisualStudio: http://msdn.microsoft.com/en-us/library/ms182068.aspx
You can use the SuppressMessage data annotation which will prevent the warning.
It looks something like this:
[SuppressMessage("Reason #Enter whatever you'd like", "ID, must match what intellsense is showing it looks something like this: IDE0001", Justification = "(optional, your own description")]
Here is a real world example:
[SuppressMessage("IntelliSenseCorrection", "IDE0001", Justification = "Do Not Remove <T> Variable, It's Required For Dapper")]
I guess you could also try to review the project or solution properties and set your warning level to a lower level or so. Otherwise, the other responses are perhaps better.