[Proposal] String literals denoting matching substrings in list pattern #7576
Unanswered
Rekkonnect
asked this question in
Language Ideas
Replies: 1 comment 4 replies
-
Yes please, I've been running into this since near the beginning of using list patterns. We should consider Syntax that came to mind first was additional constant spreads, rather than listing the string as an element of the list pattern: This would clear the way for constants to be used: |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
An enhanced way to denote substrings when matching a string using list patterns.
Motivation
Currently, using list patterns against strings for capturing a simple variable within a specific region is inconvenient, as you would have to specify each character individually. Take for example matching field names denoting backing fields for specific properties (they are in the form
<PropertyName>k__BackingField
). The only available syntax currently is this:Specifying each character individually defeats the purpose of using list patterns altogether, a better approach would be to use a combination of
StartsWith
andEndsWith
, and defining a generic intermediate string capturing method like so.Design
Strings are very well-known types, and string literals have special casing in many a cases. In this one, a proposed way is to allow raw string literals inside a list pattern involving
IEnumerable<char>
types, including astring
. With the above example in mind, the following should be legal:This would mean that
name
starts with'<'
and ends with">k__BackingField"
, while also capturing the value in between the two affixes, into the variablepropertyName
. String literals inside a list pattern overchar
values would be handled with that in mind.Bonus
With the above use case in mind, and with the fact that most list patterns over char sequences are for this purpose, we could utilize the
StartsWith
andEndsWith
methods that are present on the underlying type, if it's astring
or a[ReadOnly]Span<char>
. In other words, the above example would exactly be lowered into (code adjusted from the SharpLab example linked above):Alternatives
As demonstrated already:
StartsWith
,EndsWith
,Substring
by hand with some arithmetic operations on the indexes.Credits
@just-ero for the example and the problem at hand
Beta Was this translation helpful? Give feedback.
All reactions