What is the purpose of a question mark after a typ

2019-01-01 00:18发布

Typically the main use of the question mark is for the conditional, x ? "yes" : "no".

But I have seen another use for it but can't find an explanation of this use of the ? operator, for example.

public int? myProperty
{
   get;
   set;
}

8条回答
零度萤火
2楼-- · 2019-01-01 00:36

int? it's shorthand for Nullable<int>, the two forms are interchangeable.

Nullable<T> is an operator that you can use with a value type T to make it accept null.

In case you don't know it: value types are types that accepts values as int, bool, char etc...

They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.

Why would you need that? Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.

I suggest you to read the Microsoft Documentation because it covers the subject quite well.

查看更多
看风景的人
3楼-- · 2019-01-01 00:38

To add on to the answers above, here is a code sample

struct Test
{
    int something;
}
struct NullableTest
{
    int something;
}
class Example
{
    public void Demo()
    {
        Test t = new Test();
        t = null;

        NullableTest? t2 = new NullableTest();
        t2 = null;
    }
}

This would give a compilation error:

Error 12 Cannot convert null to 'Test' because it is a non-nullable value type

Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)

查看更多
余欢
4楼-- · 2019-01-01 00:42

practical usage:

public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
  if (value == null)
  {
    return "bad value";
  }

  return someFunctionThatHandlesIntAndReturnsString(value);
}
查看更多
低头抚发
5楼-- · 2019-01-01 00:43

Nullable Types

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a [Nullable<Int32>], pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A [Nullable<bool>] can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

查看更多
千与千寻千般痛.
6楼-- · 2019-01-01 00:46

It is a shorthand for Nullable<int>. Nullable<T> is used with value types that cannot be null.

查看更多
弹指情弦暗扣
7楼-- · 2019-01-01 00:54

it declares that the type is nullable.

查看更多
登录 后发表回答