Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress "Member is never assigned to" warning in C#

I have the following code:

ViewPortViewModel _Trochoid;
public ViewPortViewModel Trochoid
{
    get { return _Trochoid; }
    set { this.RaiseAndSetIfChanged(value); }
}

using ReactiveUI INPC support. The compiler is always warning me that Trochoid is never assigned to and will always be null. However due to the magic that RaiseAndSetIfChanged performs through CallerMemberName support, the code does work and the compiler is wrong.

How do I cleanly suppress these warnings in my code?

like image 461
bradgonesurfing Avatar asked Feb 08 '13 08:02

bradgonesurfing


2 Answers

How to cleanly suppress these warnings in my code

An alternative to an inappropriate assignment would be to just a #pragma:

#pragma warning disable 0649 // Assigned by reflection
ViewPortViewModel _Trochoid;
#pragma warning restore 0649

That should work, and it keeps the ugliness at exactly the place that it makes sense to document it - at the field declaration.

If you have multiple fields handled in the same way, you could put them all in the same "block" of disabled warnings, with a comment applicable to all of them.

Whether you view this as "clean" or not is a matter of taste, of course. I think I prefer it to assignments which are only there for the side-effect of removing the warnings.

like image 147
Jon Skeet Avatar answered Sep 29 '22 10:09

Jon Skeet


Now that every platform has CallerMemberNameAttribute support in ReactiveUI, there's no need to suffer the oppression of your Obsessive Compulsive Compiler:

ViewPortViewModel _Trochoid;
public ViewPortViewModel Trochoid
{
    get { return _Trochoid; }
    set { this.RaiseAndSetIfChanged(ref _Trochoid, value); }
}

The other overloads are really unnecessary now, but I leave them in because removing them is a breaking change and therefore won't be done until ReactiveUI 5.0

like image 45
Ana Betts Avatar answered Sep 29 '22 09:09

Ana Betts