Is there an int? value type or reference type?

? this question more likely to add ? to type of values ​​than to int?

In C #, an int is the value type. Is int? value type or reference type?

In my opinion, this should be a reference type, since it can be null .

+6
source share
4 answers

int? equivalent to Nullable<int> , which means it is a structure .

So this means the type of value .

In my opinion, this should be a reference type, since it can be null.

Your guess is wrong. From the documentation;

A nullable structure represents a type of value that can be assigned null . The Nullable structure only supports the use of a value type as a type with a null value, since reference types can be null by design.

Thus, it has 2 meanings;

  • Data value
  • A boolean value that defines the values ​​whether it was set or not. ( Nullable<T>.HasValue )
+21
source

Null types are instances of System.Nullable struct Therefore int? is the type of value.

+2
source

int? not a reference type. This is a struct (value type).

It has its own value, such as a regular int, plus the optional null value. With Nullable types, you can check if a value is relevant with HasValue .

MSDN

+1
source

EDIT I ​​had to start with this example in 1st place:

Think about transfers. Each enumerated number that we write automatically extends Enum , which is a class. Therefore, the types of values ​​that we write extend the class written by the .NET command, which is a reference type.

You can divide the world of types in two ways:

  • whether they contain null or not
  • whether they are value types or not

All combinations are possible in theory. If I'm not mistaken, at least in C #, a combination of reference types that cannot be null gives an empty set. There is no example for this combination.

In principle, all other 3 combinations are possible:

  • types that can be empty and are value types
  • types that cannot be empty and are value types
  • types that can be null and are reference types

The nature of being either a value type or a reference type has nothing to do with null (at least in how languages ​​should be designed and used, and not based on actual technical data below).

Value types are types that cause assignment between variables, parameters, and fields to fully clone an instance. Link types are types that do not.

This has nothing to do with null or with the type of memory that is occupied by the instances (whether it be a stack, a heap, or something else).

0
source

Source: https://habr.com/ru/post/953634/


All Articles