1

I've inherited a C# MVC web app at my work and there is an assignment directly inside of a controller class that looks like this:

public class FooController : Controller
{
    private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;
}

Visual Studio highlights it with an error, something like "; expected". But it compiles and runs just fine. If I change the "=>" to a simple assignment "=", it highlights HttpContext with an error "An object reference is required for the non-static field bla bla bla..." and it won't compile.

So here's my question. Why does using the "=>" operator compile and work properly? I'm new to C# (came from Android/iOS development) so while it's easy enough to understand some things, stuff like this perplexes me.

whitaay
  • 493
  • 1
  • 6
  • 18
  • 1
    Someone will enlighten you further but the `=>` is a special syntax introduced in c# 6.0 and it is and expression bodied function. It sounds like your instance of VS and your runtime environment are targeting different versions – Callback Kid Jan 25 '17 at 23:00
  • 1
    Possible duplicate of [What is the => assignment in C# in a property signature](http://stackoverflow.com/questions/31764532/what-is-the-assignment-in-c-sharp-in-a-property-signature) – Filburt Jan 25 '17 at 23:03

1 Answers1

12

=> isn't an assignment. It's a shortcut, syntactic sugar added in C# 6, and is called "Expression-bodied function members".

It's the same thing as:

private IAuthenticationManager AuthenticationManager
{
    get { return HttpContext.GetOwinContext().Authentication; }
}

Edit: Adding comment from BradleyDotNET to clarify answer:

More specifically; it works over assignment because it is returning a method call in a property getter, not trying to assign a method return value to a class member at initialization time (which isn't allowed)

For more information, see this MSDN article.

  • 1
    I love this addition in C# 6, and I use it all the time. Having a group of single-line read-only properties looks amazing compared to a cluster of properties with the pre-6 syntax. I'm also looking forward to the C# 7 changes in which they expand the behavior by adding an option to do something similar with the setter as well. – Abion47 Jan 25 '17 at 23:03
  • 1
    It's not that much sugar considering how similar it is to the use in lambda expressions. It's nicely consistent. – Jon Hanna Jan 25 '17 at 23:08
  • @BradleyDotNET that made it much clearer to me. Thank you. – whitaay Jan 25 '17 at 23:10
  • 1
    Minor nitpick after reading your link: When used to declare a getter-only property, it's called an "expression bodied property", and when used to declare a function it is an "expression bodied function". `string Method() => "test";` of course does not expand to `string Method() { get { return "test"; } }` – Quantic Jan 25 '17 at 23:12