Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# object vs. object? (nullable object)

Short question - what is difference between object and object? (nullable object)?

I know what nullable types are and for example with numbers it makes perfect sense, but what is the point of nullable object, when object by itself can be null. Am I missing something?

Story behind. I had project in Core 5.0 and 3.1, both had background tasks and based on Microsoft doc, I had function with object parameter like this:

private void DoWork(object state)
{
   //some code
}

Example from Microsoft documentation - Core 5.0

But in Core 6.0 there are some changes and now it looks like this:

private void DoWork(object? state)
{
   //some code
}

Example from Microsoft documentation - Core 6.0

Which now triggers Warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

It is not much of a issue, but more like a curiosity. Thanks in advance.

like image 907
Martin Avatar asked Sep 23 '26 02:09

Martin


1 Answers

First: T? is syntax sugar for the Nullable<T>

Microsoft added this pattern in .Net Core 6 for all owned libraries, so you can doing this.
I'ts just to warn you that there may be null in here.

when you add <Nullable>enable</Nullable> tag to project file, enable this ability of compiler.

like image 128
thisisnabi Avatar answered Sep 26 '26 15:09

thisisnabi