Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the integer reference type in C#?

Tags:

c#

I'd like to have an integer variable which can be set to null and don't want to have to use the int? myVariable syntax. I tried using int and Int16 to no avail. Do I have to use int? myVariable?

I mentioned this because in Java there is both an 'int' type (a primitive) and 'Integer' (a reference type). I wanted to be sure that there isn't a built-in integer reference type that I could be using. I'll use 'int?' for what I'm doing.

like image 927
Jon Onstott Avatar asked Jan 28 '10 06:01

Jon Onstott


People also ask

Is int a reference type in C?

Int is certainly not a reference type in C#. It's a numerical struct, which is a value type. When talking about C#, it is incorrect to say int is a reference type.

Is int a reference type?

int? is not a reference type. It is a struct (value type). It has its own value like a normal int plus an additional "null" value. With Nullable types, you can check if it has a value using HasValue .

Why int is value type and String is reference type?

The data type Integer is a value type, but a String is a reference type. Why? A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.

Which data type is a reference type?

Examples of reference data types are class, Arrays, String, Interface, etc. Examples of primitive data types are int, float, double, Boolean, long, etc.


2 Answers

Yes you should use nullable types

See Nullable

Nullable<int> Nullable<float> 

or simply

int? float?

PS:

If you don't want to use ? notation or Nullable at all - simply use special structures for such a thing. For example DataTable:

var table = new DataTable();
table.Columns.Add('intCol',typeof(int));
var row = table.NewRow();
row['intCol'] = null; //
like image 70
Sergey Mirvoda Avatar answered Oct 05 '22 10:10

Sergey Mirvoda


For info, int? / Nullable<T> is not a reference-type; it is simply a "nullable type", meaning: a struct (essentially and int and a bool flag) with special compiler rules (re null checks, operators, etc) and CLI rules (for boxing/unboxing). There is no "integer reference-type" in .NET, unless you count boxing:

int i = 123;
object o = i; // box

but this creates an unnecessary object and has lots of associated other issues.

For what you want, int? should be ideal. You could use the long-hand syntax (Nullable<int>) but IMO this is unnecessarily verbose, and I've seen it confuse people.

like image 39
Marc Gravell Avatar answered Oct 05 '22 10:10

Marc Gravell