3

I have a class that uses some services. I need each service to be instantiated on creation of the class. In C# 6 I can see 2 ways of doing this but I'm not sure which would be correct...

protected static SomeServiceType Service => new SomeServiceType();

alternatively I could use an autoproperty initialiser...

protected static SomeServiceType Service { get;} = new SomeServiceType();

What are the advantages/drawbacks with each approach? Many thanks

Simon Ryan
  • 212
  • 1
  • 9

1 Answers1

8

I believe

  • the former ("Expression-bodied members") calls new SomeServiceType() every time the property is read
  • the latter ("Auto-property initializers") calls it once on instantiation, and returns the created instance every time the property is read.

It sounds like you want the latter.

Rawling
  • 49,248
  • 7
  • 89
  • 127