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.

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

Leave a Reply

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

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s


A great site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: