How to assign an expression to a method in C#6

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to How to assign an expression to a method in C#6

  1. Pingback: Expression bodied members in constructors and get-set properties in C# 7.0 | Fitness Promotions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: