user11612444
user11612444

Reputation:

How can I convert the instantiation of an object to a lambda expression

Excuse me, is it possible to convert that code to lambda expression

var person = new Person();
person.Age = 17;
person.FirstName = "Todor";
person.SecondName = "Todorov";

Upvotes: 0

Views: 122

Answers (2)

Mong Zhu
Mong Zhu

Reputation: 23732

it's quite useless but yes:

Func<Person> person = () =>
{
    return new Person()
    {
        Age = 17,
        FirstName = "Todor",
        SecondName = "Todorov"
    }
};

This approach will create some sort of a readonly variable, because every time that you call it you will get a new instance with the hard coded values.

Another approach could be to make a generator function:

Func<int, string, string, Person> generatePerson = (int a, string f, string s) =>   
{
    return new Person()
    {
        Age = a,
        FirstName = f,
        SecondName = s
    };
};

This is like an external constructor that will generate you different objects which you can parametrize

var person = generatePerson(17, "Todor", "Todorov");

You can also skip the declaration of the input types:

Func<int, string, string, Person> generatePerson = (a, f, s) =>....

I did it for clarity reasons above.

Upvotes: 2

Sachin Vishwakarma
Sachin Vishwakarma

Reputation: 884

one of the short thing you can do is

new Person(){
Age = 17,
FirstName = "Todor",
SecondName = "Todorov"
};

Upvotes: -1

Related Questions