What do you think about using properties as initializers of objects in C #;

I was wondering what people thought about using properties as object initializers in C #. For some reason, this seems to violate the basics of what constructors are used for.

Example...

public class Person
{
    string firstName;
    string lastName;

    public string FirstName
    {
      get { return firstName; }
      set { firstName = value; }
    }

    public string LastName
    {
      get { return lastName; }
      set { lastName= value; }
    }
}

Then initialize the object with .....

Person p = new Person{ FirstName = "Joe", LastName = "Smith" };
Person p = new Person{ FirstName = "Joe" };
+3
source share
12 answers

What you see here is some kind of syntactic sugar provided by the compiler. Under the hood, what he really does is something like:

Person p = new Person (FirstName = "Joe", LastName = "Smith");

Person _p$1 = new Person();
_p$1.FirstName = "Joe";
_p$1.LastName = "Smith";
Person p = _p$1;

So, IMHO, you don’t actually break the basics of the constructor, but use a good language artifact to facilitate readability and ease of maintenance.

+10

. , , .

# .

var v = new { Foo = 1, Bar = "Hi" };
Console.WriteLine(v.Bar);
+6

. , ; .

+4

#, , :

:

string firstName;

public string FirstName
{
  get { return firstName; }
  set { firstName = value; }
}

:

public string FirstName { get; set; }
+2

, . - . , , , .

+2

, , . , , get/set. , .

+1

, ...

:

public class Person
{
    public string FirstName { get; set; }
    public string LastName {get; set; }
}

, , , Name First Last.

+1

, (linq)

var qry = from something in listofsomething
          select new {
                        Firstname = something.FirstName,
                        Lastname = something.Surname
                      }
0

, , . , , , .

, , ​​ , LINQ.

0

Nescio - , . DB.

0

, private :

public class SomeObject
{
    private SomeObject()
    {}

    public SomeObject(string someString) //enforced constructor
    {}

    public string MyProperty { get; set; }
 }

, :

var myObject = new SomeObject { MyProperty = "foo" } //no method accepts zero arguments for constructor

, . , , , .

0
I am not even happy with them. I don’t think they have a place in the constructor, or MS should go back and reorganize them so that you can use them in a private fasion. If I build an object, I want to pass some PRIVATE data. I want it to be installed from the outside world once and that. Using Object Initializers, you allow the modification of values ​​passed to the constructor.

Perhaps in the future they will change that.

0
source

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


All Articles