❔ Class method construction using lambda?
I was looking at some Avalonia code and I noticed this code
internal class Database
{
public IEnumerable<TodoItem> Get
public IEnumerable<TodoItem> GetItems() => new[]
{
new TodoItem{Description = "Walk the dog" },
new TodoItem{Description = "Buy some milk"},
new TodoItem{Description = "Learn Avalonia", isChecked = true }
};
I'm confused about the => new[] part. If the method had just been
public IEnumerable<TodoItem> GetItems()
{
new TodoItem{Description = "Walk the dog" },
new TodoItem{Description = "Buy some milk"},
new TodoItem{Description = "Learn Avalonia", isChecked = true }
};
I wouldn't have batted an eye. Does => new[] just mean collect the results in a curly brace into an array? What is this feature called?
3 Replies
the second one should absolutely have rang your alarm bells
because that's invalid syntax and would not compile
what you have there is an expression bodied method
it is equivalent to
instead of writing the
return
keyword, since the method only contains a singular operation, you can replace it with => returnValue
what you have there is an expression bodied methodThat's what I was looking for. I understand now. Thank you!
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.