Skip to content

Instantly share code, notes, and snippets.

@ChrisMissal
Last active September 14, 2017 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisMissal/320122fb8cc9411b4fec5691220a162b to your computer and use it in GitHub Desktop.
Save ChrisMissal/320122fb8cc9411b4fec5691220a162b to your computer and use it in GitHub Desktop.
Auto property initializers vs Expression-bodied members. Explained here: http://thebillwagner.com/Blog/Item/2015-07-16-AC6gotchaInitializationvsExpressionBodiedMembers
public class Test
{
public class Name
{
public string Text { get; set; }
}
public abstract class Widget
{
public abstract Name Name { get; }
}
public class Cog : Widget
{
public override Name Name => new Name { Text = "Cog" };
}
[Fact]
public void what_the_heck()
{
Widget widget = new Cog();
widget.Name.Text = "New Cog";
Assert.Equal(widget.Name.Text, "New Cog");
}
}
public class Test
{
public class Name
{
public string Text { get; set; }
}
public abstract class Widget
{
public abstract Name Name { get; }
}
public class Cog : Widget
{
public override Name Name { get; } = new Name { Text = "Cog" };
}
[Fact]
public void what_the_heck()
{
Widget widget = new Cog();
widget.Name.Text = "New Cog";
Assert.Equal(widget.Name.Text, "New Cog");
}
}
@mykeels
Copy link

mykeels commented Sep 14, 2017

The first is supposed to fail ... Everytime you access the Name variable in the Cog class, it returns a new instance of Name.

Even if Text is set, it would revert to default when Name is accessed again, making the Assert.Equal fail

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment