Nullable property in C#

Asked

Viewed 103 times

4

I was looking at some tutorials and suddenly I saw this property public Nullable<int> Id {get; set;}. What it means and when I would use it?

3 answers

4


What you were calling an attribute (the question was edited) is actually a property. The public in isolation is an attribute that determines the visibility of the property. The Nullable<int> alone is an attribute indicating the type of this property.

It indicates that you have an integer type that accepts null value. It is necessary to encapsulate the type by value because it does not have one of the values of the integer that could be considered invalid, so an extra field is used to mark when it is null. Although it works, in fact no one who knows how to program makes use of it, it is much easier and clean to use int? which is the same thing, it ends up turning into the Nullable<int>.

It is even better to use the compact form provided by the language because in C# 8 there will be nullable types by reference, and as these types have an invalid natural value they do not need the Nullable<T> and then use the full form in the type by value is asymmetrical with the type by reference.

You can see more in What is the purpose of "interrogation" in the type declaration in C#?.

If you want you can see the source of this struct.

2

Basically the public Nullable<int> Id {get; set;} is a property of the type int which can receive the null value, you can also represent in this way public int? Id { get; set; }.

1

normal Int does not accept the null value as it generates build error. However typed in this way (Nullable x) it now accepts.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.