How can I make my string property nullable?

前端 未结 9 997
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 00:08

I want to make the Middle Name of person optional. I have been using C#.net code first approach. For integer data type its easy just by using ? operator to make

相关标签:
9条回答
  • 2020-12-14 00:12

    C# 8.0 is published now so you can make reference types nullable too. For this you have to add

    #nullable enable
    

    Feature over your namespace. It is detailed here

    For example something like this will work:

    #nullable enable
    namespace TestCSharpEight
    {
      public class Developer
      {
        public string FullName { get; set; }
        public string UserName { get; set; }
    
        public Developer(string fullName)
        {
            FullName = fullName;
            UserName = null;
        }
    }}
    

    Also you can have a look this nice article from John Skeet that explains details.

    0 讨论(0)
  • 2020-12-14 00:14

    string is by default Nullable ,you don't need to do anything to make string Nullable

    0 讨论(0)
  • 2020-12-14 00:15

    It's not possible to make reference types Nullable. Only value types can be used in a Nullable structure. Appending a question mark to a value type name makes it nullable. These two lines are the same:

    int? a = null;
    Nullable<int> a = null;
    
    0 讨论(0)
  • 2020-12-14 00:16

    string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

    public struct Nullable<T> where T : struct
    

    Which means that whatever type is replaced for the generic parameter, it must be a value type.

    0 讨论(0)
  • 2020-12-14 00:24

    System.String is a reference type so you don't need to do anything like

    Nullable<string>
    

    It already has a null value (the null reference):

    string x = null; // No problems here
    
    0 讨论(0)
  • 2020-12-14 00:25

    String is a reference type and always nullable, you don't need to do anything special. Specifying that a type is nullable is necessary only for value types.

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