How to initialize a string to "" when using an automatically implemented property

How can I set the string to "" when using an automatically implemented property, for example:

public string Blah {get; set;}
+3
source share
8 answers

You indicated that you use it for a strongly typed representation, so I don’t even have a constructor for it. If you do not have access to the constructor, it seems like you should not use a property that is implemented automatically.

+7
source

When you use an auto property like this, the default value for a property type is a value unless you initialize it elsewhere, for example, in a constructor:

public class Person
{
    public string Name { get; set; }

    public Person()
    {
        Name = string.Empty;
    }
}

, ( ), - , null, .

, .

auto :

public class Person
{
    public string Name { get; private set; }

    public Person()
    {
        Name = string.Empty;
    }
}

- . , ?? (null-coalescing) :

public class Person
{
    public string Name 
    { 
        get { return mName; }
        set { mName = value ?? string.empty; }
    }

    public Person()
    {
        Name = string.Empty;
    }

    private string mName;
}
+10

...

Blah = String.Empty;

... , default (string) . , default (string) null. .:)

+2

( )...

public MyClass()
{
    Blah = string.Empty;
}
+2

, ,

  private string Blah = "";

  public string Bleh {
     get { return Blah;  }
     set { Blah = value; }
  }
+2

, "" . .

+2

, ? . string.IsNullOrEmpty(p.Name).

0

.

  • string = empty → , .
  • string = null → , , .
0

Source: https://habr.com/ru/post/1711959/


All Articles