This is a use of the switch
keyword which I have not seen before:
public TestUserType UserType { get; private set; } = TestUserType.None;
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var task = this.UserType switch
{
TestUserType.Admin => Task.FromResult(new AuthenticationState(this.Admin)),
TestUserType.User => Task.FromResult(new AuthenticationState(this.User)),
TestUserType.None => Task.FromResult(new AuthenticationState(this.Anonymous)),
_ => Task.FromResult(new AuthenticationState(this.Visitor))
};
return task;
}
Can someone explain this use of 'switch'? I checked the docs, but I only found the usual switch (var)
usage.
CodePudding user response:
This is known as a switch expression. Unlike the traditional switch statements, switch expressions return a value.
Furthermore, they support concepts such as pattern matching which is a far more expressive syntax than (used to be) allowed by traditional case
statements. But as Hans points out below, the switch statement also supports pattern matching.
CodePudding user response:
Equivalent in old notation:
switch(UserType)
{
case TestUserType.Admin:
return Task.FromResult(new AuthenticationState(this.Admin));
case TestUserType.User:
return Task.FromResult(new AuthenticationState(this.User));
case TestUserType.None:
return Task.FromResult(new AuthenticationState(this.Anonymous));
default:
return Task.FromResult(new AuthenticationState(this.Visitor));
}