What is the purpose of a question mark after a type (for example: int? myVariable)?

前端 未结 8 2310
盖世英雄少女心
盖世英雄少女心 2020-11-22 10:26

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 explanat

8条回答
  •  天命终不由人
    2020-11-22 10:50

    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)

提交回复
热议问题