How to set null value to int in c#?

2019-01-23 10:52发布

int value=0;

if (value == 0)
{
    value = null;
}

How can I set value to null above?

Any help will be appreciated.

7条回答
看我几分像从前
2楼-- · 2019-01-23 10:54

You cannot set an int to null. Use a nullable int (int?) instead:

int? value = null;
查看更多
放我归山
3楼-- · 2019-01-23 11:04

Additionally, you cannot use "null" as a value in a conditional assignment. e.g...

bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;

FAILS with: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

So, you have to cast the null as well... This works:

int? myint = (testvalue == true) ? 1234 : (int?)null;
查看更多
我命由我不由天
4楼-- · 2019-01-23 11:04

int does not allow null, use-

int? value = 0  

or use

Nullable<int> value
查看更多
再贱就再见
5楼-- · 2019-01-23 11:10

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

查看更多
Root(大扎)
6楼-- · 2019-01-23 11:15

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:

int? value = 0;

if (value == 0)
{
    value = null;
}

Further Reading

查看更多
迷人小祖宗
7楼-- · 2019-01-23 11:18
 public static int? Timesaday { get; set; } = null;

OR

 public static Nullable<int> Timesaday { get; set; }

or

 public static int? Timesaday = null;

or

 public static int? Timesaday

or just

 public static int? Timesaday { get; set; } 


    static void Main(string[] args)
    {


    Console.WriteLine(Timesaday == null);

     //you also can check using 
     Console.WriteLine(Timesaday.HasValue);

        Console.ReadKey();
    }

The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null

查看更多
登录 后发表回答