Context class - default!;

Dean Everhart 1,496 Reputation points
2023-03-18T12:34:11.2866667+00:00

I'm using an older version of .net to model creating property sets in the context class of a core 6 project. I notice in the core 6 project they include "= default!;" at the end.

having a hard time finding an explanation of the "= default!;" online. One explanation is a default value for a property, but this is a property set in a context class.

what is the = default!; in core 6 context class?

        public DbSet<Media.Models.Reference> Reference { get; set; } = default!;
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,132 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,241 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,181 Reputation points
    2023-03-18T13:21:10.2066667+00:00

    There are a couple things going on.

    Since C# 6 properties can be assigned an initial value.

    The default literal sets default value of a type. For a C# class that means null.

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/default#default-literal

    If you try to set the property to default without the "!" then you'll see a warning. "CS8625 - Cannot convert null literal to non-nullable reference type."

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/nullable-warnings?f1url=%3FappId%3Droslyn%26k%3Dk(CS8625)

    Adding the "!" (C# ! (null-forgiving) operator) overrides the warning.

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful