C
C#2y ago
Decabytes

❔ 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
ero
ero2y ago
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
public IEnumerable<TodoItem> GetItems()
{
return new TodoItem[]
{
new TodoItem { Description = "Walk the dog" },
new TodoItem { Description = "Buy some milk" },
new TodoItem { Description = "Learn Avalonia", isChecked = true }
};
}
public IEnumerable<TodoItem> GetItems()
{
return new TodoItem[]
{
new TodoItem { Description = "Walk the dog" },
new TodoItem { Description = "Buy some milk" },
new TodoItem { Description = "Learn Avalonia", isChecked = true }
};
}
instead of writing the return keyword, since the method only contains a singular operation, you can replace it with => returnValue
Decabytes
DecabytesOP2y ago
what you have there is an expression bodied method
That's what I was looking for. I understand now. Thank you!
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server