sesamii seed
sesamii seed

Reputation: 739

How to make reference type nullable in C# 7.3?

I can't upgrade Net for now. I want to achieve this public SiteOptionModel? Site { get; set; } like bool?. But it says I should upgrade .Net but I am afraid, upgrading .Net will destroy quite a big project. Is there any way to achieve this?

public bool IsVisibleInGrid { get; set; }
public SiteOptionModel? Site { get; set; }
public bool? IsDeleted { get; set; }

LinQ query showing error not having SiteId

from truck in database.Truck
   where truck.CarrierId == carrierId
         && (truck.IsDeleted == null || truck.IsDeleted == false)
   orderby truck.Code
   select new CarrierDetailViewModel.TruckModel2
   {
       Id = truck.TruckId,

       Site = new CarrierDetailViewModel.SiteOptionModel{
            Id = (int)truck.SiteId,
            Name = truck.Site.Name,
            Code = truck.Site.Code
       }
   } ;

Error

Severity Code Description Project File Line Suppression State Error CS8370 Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.

Upvotes: 12

Views: 53090

Answers (1)

Theraot
Theraot

Reputation: 40160

The compiler is asking you to use a newer version of the language, not a newer version of .NET. Every version of .NET supports nullable references types. References could be null in any version of .NET, you just were not able to annotate that in C# until C# 8.0.

However, your project is configured for C# 7.3, you need to change the language version. Please refer to How to enable Nullable Reference Types feature of C# 8.0 for the whole project.

See also What is the difference between C# and .NET?

Once you have your project configured for C# 8.0 and with Nullable Reference Types enabled… Roslyn, the C# compiler, will understand nullability annotations and provide code analysis based on them.

And you will have to deal with null anyway. Which might mean null checks. Accessing a member of a null reference is still an NullReferenceException, even in C# 8.0. At least the static analysis will help you.

Refer to What is a NullReferenceException, and how do I fix it?.


On the odd chance that you actually need to run newer features on an old runtime (e.g. async/await in .NET 2.0), I might have a solution for you: Theraot.Core. Of which, full disclosure, I'm the author.

Upvotes: 12

Related Questions