Disable/suppress warning CS0649 in C# for a specific field of class

C#Suppress Warnings

C# Problem Overview


I have some fields in a C# class which I initialize using reflection. The compiler shows CS0649 warning for them:

> Field foo' is never assigned to, and will always have its default > value null' (CS0649) (Assembly-CSharp)

I'd like to disable the warning for these specific fields only and still let the warning be shown for other classes and other fields of this class. It is possible to disable CS0649 for the whole project, is there anything more fine-grained?

C# Solutions


Solution 1 - C#

You could use #pragma warning to disable and then re-enable particular warnings:

public class MyClass
{
    #pragma warning disable 0649

    // field declarations for which to disable warning
    private object foo;

    #pragma warning restore 0649

    // rest of class
}

Refer to Suppressing “is never used” and “is never assigned to” warnings in C# for an expanded answer.

Solution 2 - C#

I believe it's worth noting the warning can also be suppressed by using inline initialization. This clutters your code much less.

public class MyClass
{
    // field declarations for which to disable warning
    private object foo = null;

    // rest of class
}

Solution 3 - C#

//disable warning here
#pragma warning disable 0649

 //foo field declaration

//restore warning to previous state after
#pragma warning restore 0649

Solution 4 - C#

public class YouClass
{
#pragma warning disable 649
    string foo;
#pragma warning restore 649
}

Solution 5 - C#

If you want to disable ALL warnings in the project (rather than per script) then do this:

Ceate a text file called mcs.rsp (for editor scripts) in your YOUR_PROJECT_NAME/Assets directory with contents (for example):

-nowarn:0649

(You can change the number to match whatever warning you want)

Original answer

Note: This doesn't disable the warnings in the Unity console if you are using Unity (I am still investigating how to remove those)

Here is some Unity documentation with more information

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniseeallView Question on Stackoverflow
Solution 1 - C#DouglasView Answer on Stackoverflow
Solution 2 - C#BMacView Answer on Stackoverflow
Solution 3 - C#Alexander BortnikView Answer on Stackoverflow
Solution 4 - C#Hamlet HakobyanView Answer on Stackoverflow
Solution 5 - C#AggressorView Answer on Stackoverflow