I tend to steer away from the null-forgiving operator to appease the compiler, instead perform necessary asserts. No matter, the best way to learn is to first read the docs rather than jumping into code.
Here is something I slapped together without the null-forgiving operator
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Data
{
public static List<Person> Persons => new()
{
new() {Id = 1, Name = "Anne" },
new() {Id = 2, Name = null }, // not needed
new() {Id = 3, Name = "Mike" },
};
}
Then
List<Person> people = Data.Persons;
people.ForEach(person => Console.WriteLine(person.Name ?? "null"));
var findName = "Mike";
Person? mike = people.Find(person => person.Name == findName);
if (mike is null)
{
Console.WriteLine($"Failed to find {findName}");
}
else
{
Console.WriteLine(mike.Id);
}
Example with null forgiving, I know the list is good.
public static List<Country> Countries()
{
var list = JsonSerializer.Deserialize<List<Country>>(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Countries.json")));
list!.Insert(0, new Country() { CountryIdentifier = -1, CountryName = "Select" });
return list;
}