-2

can someone explain to me the diffrence between default and default!

for example:

public string FirstName { get; set; } = default!;

to:

public string FirstName { get; set; } = default;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    `!` is *null forgiving operator*, so you assign `default` value (which is `null` in case of `string`) and do not want to get warning for this: note that `FirstName` is of type `string`, not `string?`. – Dmitry Bychenko Dec 13 '22 at 11:20
  • From an IL-perspective both statements are identical. The null-forgiving operator is just an indicator for the compiler to **not** throw a warning if you attempt to assign `null` to a non-nullable reference-type – MakePeaceGreatAgain Dec 13 '22 at 11:24

1 Answers1

4

Well, ! is a null forgiving operator. In your case you assign default value (which is null in case of string) to string property and don't want to get warning:

 // FirstName should not be null
 // but you assign default (null) value to it
 // and don't want to get warning about it (you know what you are doing)
 public string FirstName { get; set; } = default!; 

Another possibility is to allow null (note string? instead of string):

 // FirstName can be null
 // We assign default (null) value to it
 public string? FirstName { get; set; } = default;

In case of

 // FirstName is not suppose to be null
 // But we assign default (which is null)
 // Compiler can warn you about it
 public string FirstName { get; set; } = default; 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215