Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
421 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...