Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the CS0649 compiler warning when I add a custom attribute?

Goal: To remove the compiler warning 'CS0649' (field is never assigned to) when I use my custom attribute.

I have a custom attribute (code below is just examples):

[AttributeUsage(AttributeTargets.Field)]
public class MyCustomAttribute : Attribute { }

I then use that attribute on a field:

[MyCustom]
private readonly SomeType someType;

My application will auto fill someType with a value so we don't need to worry about initializing it.

I will still get a squiggly line in Visual Studio under someType and the warning message "Field "someType" is never assigned to, and will always have it's default value null."

Is there an attribute or other means that I can add to MyCustomAttribute that will remove this compiler warning?

NOTE: I do not want to have to modify the field or type the field is within further. I simply want to add the attribute and the warning go away.

like image 765
Michael Puckett II Avatar asked Nov 06 '22 23:11

Michael Puckett II


1 Answers

There are only two ways to get rid of a warning:

  1. Use #pragma warning disable/restore, or
  2. Suppress a warning for your entire project in the project Properties -> Build -> and put the warning number in 'Suppress warnings'.

But that's it.

But that's why it's a warning and not an error. Warnings are there to flag things that are fishy, but could very well be legitimate. A field that is never set within the class itself is fishy, but not necessarily an error.

The #pragma directives are the best way to get rid of them since it's explicitly shows that you've acknowledged the warning and deemed it unfounded.

like image 170
Gabriel Luci Avatar answered Nov 14 '22 04:11

Gabriel Luci