tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Back to C# basics: Difference between "=>" and "{ get; } =" for properties

11 Nov 2020 1 mins .NET

I recently realized, the difference between => and { get; } = for properties might not be as known as everybody thinks, based on code I saw multiple times.

Here’s an example code.

public class C
{
	public Foo A { get; } = new Foo();
	public Foo B => new Foo();
}

Is it the same or is it not? The answer is, it’s not the same. The A property is property with getter only (aka read only or immutable property). When C instance is created a new instance of Foo is assigned to the property and will be returned from now on. The B property defines also only getter, but this time the getter contains the new Foo(); as it’s body, aka returning new instance of Foo every time you access B.

Putting it into barebone C#, it would look like this.

public class C
{
	readonly Foo _a = new Foo();
	
	public Foo A
	{
		get { return _a; }
	}

	public Foo B
	{
		get { return new Foo(); }
	}
}

Makes sense?

Profile Picture Jiří Činčura is an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.