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;
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;
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;