How to assign an expression to a method in C#6
February 15, 2016 1 Comment
In this post we saw how to assign expressions to class properties in C# 6 using the lambda operator “=>”:
public string FullName => string.Format("{0} {1}", FirstName, LastName);
This property getter was part of a Person class:
public class Person { public int Age { get; } public string FirstName { get;} public string LastName { get; } public string FullName => string.Format("{0} {1}", FirstName, LastName); public Person(string firstName, string lastName, int age) { FirstName = firstName; LastName = lastName; Age = age; } }
The same type of syntax exists for one-liner functions. It’s really just syntactic sugar which saves you a return statement and the brackets.
Let’s add a Dog class:
public class Dog { public string Name { get; } public int Age { get; } public Dog(string name, int age) { Name = name; Age = age; } }
Back in the Person class we’ll add a method called “WalkDog”:
public void WalkDog(Dog dog) => Console.WriteLine("I'm taking {0} out for a walk", dog.Name);
If for whatever reason you’d like to calculate the combined age of a Person and a Dog you can have a function with a return value like this:
public int GetCombinedAge(Dog dog) => Age + dog.Age;
These are “normal” methods so you can call them accordingly:
Person p = new Person("John", "Smith", 28); p.WalkDog(new Dog("Caesar", 3)); int combined = p.GetCombinedAge(new Dog("Caesar", 3));
View all various C# language feature related posts here.
Pingback: Expression bodied members in constructors and get-set properties in C# 7.0 | Fitness Promotions