Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDE0057 Substring can be simplified

Tags:

c#

.net

roslyn

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.

like image 940
Mr. Cooper Avatar asked Jun 19 '26 02:06

Mr. Cooper


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 were 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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges

like image 189
Mr. Cooper Avatar answered Jun 21 '26 16:06

Mr. Cooper