开发者

C# syntax question [duplicate]

This question already h开发者_如何学JAVAas answers here: Closed 11 years ago.

Possible Duplicate:

? (nullable) operator in C#

What does the ? do used like this:

class Test
{
    public int? aux;
}

It's probably a simple question for someone more familiar with c#, but I don't really know what to search for. I read an explanation but didn't fully understand it. I would also be interested in knowing what the "??" operator does. Some examples on where they would be useful would be of great help.


This (int?) is shorthand for Nullable<int>.


It can be any int value plus an additional null. See more info Nullable Types

The purpose of using Nullable int is while often using database operations, there are conditions where some value might be null and we have to express in code. For Example consider the folowing schema

Employee

 - id,  bigint, not null
 - name,  nvarchar(100), null
 - locationId,  bigint, null

Suppose locationId of an employee is not available, so in database the value of locationid of employee is NULL. On C# side, you know that int can not have a NULL value, so type, Nullable int(and few others) has been added, due to which we can easily show that locationId has no value.


"?" denotes a nullable type


int? means nullable integer: aux can have an int value or be null!!


As many others have already answered, the ? denotes nullable types. This means that a variable of type int? can be assigned null in addition to an integer values.
This is used when you want to distinguish the case of a variable which has not been initialized from the case in which it has been assigned the default value.
For instance you can consider the case of bool. When you declare a bool variable, it has the false value by default. This means that when its value is false you can't tell if this happens because someone has assigned the variable that value, of because nobody touched it. In this case a bool? is useful since it allows you to distinguish a "real" false value (explicitely assigned by some code) from the not initailized case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜