3

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.

4
  • So you're essentially asking "what is the point of nullable reference types?" Commented May 18, 2022 at 9:57
  • 4
    This is a new feature called nullable reference types. There is little overlap with Nullable for value types, although it uses the same syntax. Commented May 18, 2022 at 9:57
  • 2
    NullReferenceException is something that has cost billions. This is a method of forcing the software developer to reduce this problem by explicitly marking an reference type to be able to contain a null value. The compiler can also get more insight into which reference is able to contain a null value and point this out to the developer. Commented May 18, 2022 at 10:04
  • Ahhh I see. I am dum dum, if only I would read that warning more carefully, then google would not always showing me this link nullable value types and I would find that doc page You sent. Now it is obvious. Thanks a lot guys. If You post it as answer, I will mark it ;) Commented May 18, 2022 at 10:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.