❔ Non-nullable field 'rating' must contain a non-null value when exiting constructor

Why am i getting this warning: Non-nullable field 'rating' must contain a non-null value when exiting constructor? Before exiting the constructor Rating = aRating is executed and thus rating should be set rating to "G" or "PG" right?
c#
internal class Book
{
private string title;
private string rating;
public Book(string aTitle, string aRating)
{
title = aTitle;
Rating = aRating;
}
public string Rating
{
get { return rating; }
set {
if(value == "G")
{
rating = value;
}
else
{
rating = "PG";
}
}
}
}
c#
internal class Book
{
private string title;
private string rating;
public Book(string aTitle, string aRating)
{
title = aTitle;
Rating = aRating;
}
public string Rating
{
get { return rating; }
set {
if(value == "G")
{
rating = value;
}
else
{
rating = "PG";
}
}
}
}
4 Replies
vdvman1
vdvman12y ago
It can't see that setting Rating always sets rating under the hood You can add [MemberNotNull(nameof(rating))] to the setter to make the compiler happy
using System.Diagnostics.CodeAnalysis;

internal class Book
{
private string title;
private string rating;

public Book(string title, string rating)
{
this.title = title;
Rating = rating;
}

public string Rating
{
get => rating;

[MemberNotNull(nameof(rating))]
set => rating = value switch
{
"PG" or "G" => value,
_ => "NR"
};
}
}
using System.Diagnostics.CodeAnalysis;

internal class Book
{
private string title;
private string rating;

public Book(string title, string rating)
{
this.title = title;
Rating = rating;
}

public string Rating
{
get => rating;

[MemberNotNull(nameof(rating))]
set => rating = value switch
{
"PG" or "G" => value,
_ => "NR"
};
}
}
(I also wrote a switch with pattern matching instead of the if statement, you can use your original setter body if you don't understand or don't like how that looks)
TradingRaws4SeoulObjectStoryRaws
Thank you! heartowo I haven't seen this way of writing a switch statement but it looks very concise. TY! 🙂
Pobiega
Pobiega2y ago
its a "switch expression". They are very very nice.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.