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

Ronald Rex 1,666 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")
};   
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
4,010 questions
C#
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.
11,341 questions
0 comments No comments
{count} votes

Accepted answer
  1. gekka 11,456 Reputation points MVP
    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.


0 additional answers

Sort by: Most helpful

Your answer

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