c# the power of pattern matching and code simplication
Consider the following code :-
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var assignmentNode = equalValueClause?.EqualsToken.Value as MemberAccessExpressionSyntax; | |
if (assignmentNode != null && assignmentNode is MemberAccessExpressionSyntax) | |
{ | |
if (assignmentNode.Expression is IdentifierNameSyntax memberAccessClause) | |
{ | |
return memberAccessClause.Identifier.ValueText; | |
} | |
} | |
And then with the power of pattern matching, it gets simplified into :-
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static string TryGetEqualsValueClause(EqualsValueClauseSyntax equalValueClause) | |
{ | |
if (equalValueClause != null) | |
return null; | |
if (equalValueClause?.EqualsToken.Value is MemberAccessExpressionSyntax assignmentNode && assignmentNode is MemberAccessExpressionSyntax) | |
{ | |
if (assignmentNode.Expression is IdentifierNameSyntax memberAccessClause) | |
{ | |
return memberAccessClause.Identifier.ValueText; | |
} | |
} | |
return null; | |
} |
Walla!!
Comments