Share via

I dont know if this code is using a Lambda expression or is this called Expression-bodied Members

Ronald Rex 1,671 Reputation points
2024-02-04T00:21:21.1666667+00:00

I am using the MVVM pattern and this is a Constructor of the ViewModel. I dont understand if this is a Lambda Expression? But I would greatly appreciate if anyone could explain to me this syntax. I understand what its doing I just would like to understand the syntax, particularly the arrow =>. And what if I wanted to have some other statements in this Constructor.

public MainPageViewModel() => Items = new ObservableCollection<Person>
{

    new Person(1,"John Smith","300 W. Main","India"),
    new Person(2,"Ron Stevenson","N. Broadway","Washington"),
    new Person(3,"Sally Smith","6700 W. Covington","Casablanca"),
    new Person(4,"Ken Jenkins","500 E. Washington","NYC")
};   
Developer technologies | .NET | .NET Multi-platform App UI
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

gekka 14,146 Reputation points MVP Volunteer Moderator
2024-02-04T04:08:59.9866667+00:00

I guessed that adding the missing code would look following code.

class MainPageViewModel
{
    public MainPageViewModel() => Items = new ObservableCollection<Person>
    {
        new Person(1,"John Smith","300 W. Main","India"),
        new Person(2,"Ron Stevenson","N. Broadway","Washington"),
        new Person(3,"Sally Smith","6700 W. Covington","Casablanca"),
        new Person(4,"Ken Jenkins","500 E. Washington","NYC")
    };

    public ObservableCollection<Person> Items { get; }
}

If this is correct, the conversion can be done as follow.

class MainPageViewModel
{
    public MainPageViewModel()
    {
        this.Items = new ObservableCollection<Person>
        {
            new Person(1,"John Smith","300 W. Main","India"),
            new Person(2,"Ron Stevenson","N. Broadway","Washington"),
            new Person(3,"Sally Smith","6700 W. Covington","Casablanca"),
            new Person(4,"Ken Jenkins","500 E. Washington","NYC")
        };
    }

    public ObservableCollection<Person> Items { get; }
}

This is the constructor that initializes the Items property.

To sum up, your presented code is Expression-bodied constructor.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.