1

In c# 9 with the new feature of Nullable reference types i find myself putting "?" on every class properties types to turn of the warning and then placing if != null outside in the code to avoid null references (and that's good). But i was wondering, is it right to spam "?" everywhere?

Let's say i have a class that represents a database record with a foreign key that is not optional:

public int UserId { get; set; }
public virtual User User { get; set; }

I expect the virtual property to be always not null (since it is instantiated by entity framework) so i don't want to make it nullable to remove the warning in the class, instead i would initialize it's value to "null!". I should then wrap the code that uses this property with a try catch block to catch an exception if entity framework won't work as expected.

What do you think? Is it safer to spam "?" and always repeat if != null everywhere?

Mazza
  • 37
  • 6
  • 5
    With C# 11 you can make these `required` properties, which avoids the issue. Before then, if you're sure that the property will be initialized by something (such as EF, or a deserializer), it's fine to declare it as `= null!` and then *not* check use sites for null – canton7 Mar 08 '23 at 08:46
  • 2
    I don't think it's necessary to check for "if entity framework won't work as expected". This can only happen if you break something during development, and a lot of things will break catastrophically if this happens. You'll probably spot the issue straight away, and any extra try/catch blocks you added will probably only get in the way. I'd say it's fine to assume that EF is working as intended in your code – canton7 Mar 08 '23 at 08:55
  • I instantly turn off nullable reference types on any new project I start :) – YungDeiza Mar 08 '23 at 09:08
  • 1
    @YungDeiza you like debugging NullReferenceExceptions? – Hans Kesting Mar 08 '23 at 09:46
  • @HansKesting I like sufficiently testing my code to eliminate bugs – YungDeiza Mar 08 '23 at 09:59
  • 4
    Then you should love having the compiler warn you of where there may be bugs before you've even written any tests ;) – canton7 Mar 08 '23 at 10:02

0 Answers0