Home > Enterprise >  Set property as nullable C#
Set property as nullable C#

Time:05-21

I have seen two approaches to setting a property as nullable. What is the difference between the two approaches? which one is clean?

public string? a { get; set; };
public string b { get; set; } = default!;

Edit 1: Updated code to correct syntax and changed int -> string

CodePudding user response:

You wrote int a?instead of int? a.

The 2 behave very differently here. An int is not nullable, its default value is 0. Therefore you can just use defuslt without the ! . The ! just makes the compiler ignore null check rules. The other creates a real null value.

Lets say we instead had: string? a = null Or string a = default! Which behave almost the same, but their type differs.

In that case the ? nullable reference type is more clean as you dont get rid of the null safety guarantees.

CodePudding user response:

The first approach is correct so to say. You can understand this clearly using snippet as below.

void Main()
{
    var pro = new Pro{
        a = 1,
        //b = 1
    };
    Console.WriteLine(typeof(int));
    Console.WriteLine(typeof(int?));
}
public class Pro {
    public int? a { get; set; }
    public int b { get; set; } = default!;  
}
  • Related