Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is `Nullable<T>?`? [closed]

Tags:

c#

nullable

I made a typo and Visual Studio didn't mark it as an error:

void Method(Nullable<SpriteFont>? font = null) { }

font shows up as SpriteFont?? in output. What did I just do?

UPD: Sorry, everyone, I didn't try co compile it, it just didn't show up as an error until I did. Still, it's weird that it looked as Type?? in output.

Furthermore SpriteFont is already nullable, so I was going to get an error anyway :(

like image 274
user1306322 Avatar asked Oct 23 '12 02:10

user1306322


People also ask

For what type do you use nullable T?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

What is the meaning of nullable?

nullable (not comparable) That may be nullified; nullifiable. quotations ▼ (computing, of a variable or object) That is allowed to have a null value.

What is a nullable data type?

The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.

What does nullable enable mean?

Nullable contexts enable fine-grained control for how the compiler interprets reference type variables. The nullable annotation context determines the compiler's behavior. There are four values for the nullable annotation context: disable: The code is nullable oblivious. Nullable warnings are disabled.


2 Answers

I have tried it here, just now... and I could not reproduce what you sayd.

All of the following statements fail to compile:

  • Nullable<int>? a = 1;
  • Nullable<Nullable<int>> b = 1;
  • Nullable<int?> a = 1;
  • void A(Nullable<Nullable<int>> a)
  • void A(Nullable<int>? a)
  • void A(Nullable<int?> a)

Using Visual Studio 2012, C# 4 or 5 I think, .Net framework 4.5.

like image 52
Miguel Angelo Avatar answered Oct 26 '22 08:10

Miguel Angelo


The editor's syntax checker failed to flag it as an error with the red squiggles. Not the compiler.

Two distinct chunks of code. They have to be, syntax checking code while you are typing it in, in essence always broken, requires a very different approach.

like image 25
Hans Passant Avatar answered Oct 26 '22 08:10

Hans Passant