C# 7 Expression Bodied Constructors

后端 未结 1 558
灰色年华
灰色年华 2020-12-01 11:47

In C# 7, how do I write an Expression Bodied Constructor like this using 2 parameters.

public Person(string name, int age)
{
  Name = name;
  Age = age;
}


        
相关标签:
1条回答
  • 2020-12-01 12:44

    A way to do this is to use a tuple and a deconstruction to allow multiple assignments in one expression:

    public class Person
    {
        public string Name { get; }
        public int Age { get; }
    
        public Person(string name, int age) => (Name, Age) = (name, age);
    }
    

    As of C# 7.1 (introduced with Visual Studio 2017 Update 3), the compiler code will now optimise away the actual construction and deconstruction of the tuple. So this approach has no performance overhead when compared with "longhand" assignment.

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