C# nullable string error

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

Later

相关标签:
6条回答
  • 2020-11-27 05:35

    You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 05:44

    String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.

    0 讨论(0)
  • 2020-11-27 05:45

    For nullable, use ? with all of the C# primitives, except for string.

    The following page gives a list of the C# primitives: http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx

    0 讨论(0)
  • 2020-11-27 05:52

    string cannot be the parameter to Nullable because string is not a value type. String is a reference type.

    string s = null; 
    

    is a very valid statement and there is not need to make it nullable.

    private string typeOfContract
        {
          get { return ViewState["typeOfContract"] as string; }
          set { ViewState["typeOfContract"] = value; }
        }
    

    should work because of the as keyword.

    0 讨论(0)
  • 2020-11-27 05:54

    System.String is a reference type and already "nullable".

    Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

    0 讨论(0)
提交回复
热议问题