C# nullable string error

前端 未结 6 1938
梦如初夏
梦如初夏 2020-11-27 05:19
private string? typeOfContract
{
  get { return (string?)ViewState[\"typeOfContract\"]; }
  set { ViewState[\"typeOfContract\"] = value; }
}

Later

6条回答
  •  抹茶落季
    2020-11-27 05:40

    Please note that in upcoming version of C# which is 8, the answers are not true.

    All the reference types are non-nullable by default and you can actually do the following:

    public string? MyNullableString; 
    this.MyNullableString = null; //Valid
    

    However,

    public string MyNonNullableString; 
    this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 
    

    The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

    More info

    To the moderator who is deleting all the answers, don't do it. I strongly believe this answer adds value and deleting would simply keep someone from knowing what is right at the time. Since you have deleted all the answers, I'm re-posting answer here. The link that was sent regarding "duplicates" is simply an opening of some people and I do not think it is an official recommendation.

提交回复
热议问题