IDE0057 Substring can be simplified

Viewed 3502

I have the following lines of code:

string line = "<!--SomeValue=\"asdf\"-->";
int start = line.IndexOf("=\"") + 2;
return line.Substring(start, line.IndexOf("\"-->") - start);

This will return asdf.

I receive IDE0057 from the code analysis. I'm thinking there's a simple way to simplify :).

Edit: The question is how do I simplify my code above to remove the IDE0057 message received. Reading the documentation provided for the message it is unclear how to fix it.

1 Answers

Gosh why didn't I know about the lightbulb. Thanks @Heretic Monkey.

string line = "<!--SomeValue=\"asdf\"-->";
int start = line.IndexOf("=\"") + 2;
return line[start..line.IndexOf("\"-->")];

In C# 8 string range operators we're introduced. IDE0057 indicates that the substring method can be simplified by using the range operator instead. The above code uses the string range operator to grab from the desired start position, take the stuff in the middle up to the ending point desired. This removes the IDE0057 message.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges

Related