Visual Studio Shortcu / Syntax for Quick Property Assignment

Let's say you have a class

public class Person

{

public int PesronId{get;set;}

public string FirstName{get;set;}

public string LastName{get;set;}

public string Gender{get;set;}

}

Now we create the object p1

Person p1 = new Person();

Next, we have values ​​from text fields that need to be assigned p1 for example.

p1.PersonId = textbox1.text;

p1.FirstName = textbox2.text; 

p1.LastName = textbox3.text;

Is there a more efficient way to do this in Visual Studio 2010 with which I will get something like this

p1.PersonId =

p1.FirstName = 

p1.LastName = 

so I don’t need to manually enter the properties for p1.

Or is this an alternative syntax that I can use.

+3
source share
2 answers

Simple syntax for code:

Person p1 = new Person
{
    PersonId = textbox1.Text,
    FirstName = textbox2.Text,
    LastName = textbox3.Text
};

This is an object initializer introduced in C # 3.

, - , . -, , , IntelliSense . , , , IMO.

Person - , # 4 , .

+6

#:

Person p1 = new Person()
{
     PersonId = textbox1.text,
     FirstName = textbox2.text,
     LastName = textbox3.text
};
+1

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


All Articles