简体   繁体   中英

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;

您可以使用Nullable<T>类型:

int? i = null;

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;

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM