user4502159
user4502159

Reputation:

Declare integer as null

Generally, we delare variable property like this:

int a = 0;

I want to declare one integer as null. how can I do that?

my expected output is

int i = null;

Upvotes: 1

Views: 903

Answers (4)

AcAnanth
AcAnanth

Reputation: 775

C# Data types are divided into value types and reference type. By default value types are not nullable. But for reference type is null.

string name = null;
Int ? i = null; // declaring nullable type

If you want to make value type as nullable use ?

Int j = i;  //this will through the error because implicit conversion of nullable 
            // to non nullable is not possible `

Use

int j =i.value;

or

int j =(int) i;

Upvotes: 4

JanuszB
JanuszB

Reputation: 68

An integer is a value type, whose default value, when initialized, is 0.

https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

You just cannot make it null, and the compiler will not let you use an uninitialized integer.

If you require a null to be assigned to an integer, for whatever reason, you should use a reference type Nullable. int? = null . I hope this helps.

Upvotes: 0

Aheho
Aheho

Reputation: 12821

Value types in c# are not-nullable unless you explicitly define them as such. If you want to allow nulls for an int you have to declare your variable like so:

int? i = null;

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You can use the Nullable<T> type:

int? i = null;

Upvotes: 10

Related Questions