Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace C# expression

Time and again I find myself needing to change the use of one method call with another.

E.g. I have 100 occurrences of method calls similar to this:

Helper.GetIntFromData(packetData.Skip(offset).Take(length).ToArray());

that need to be changed to

Helper.GetIntFromData(packetData, offset, length);

This is relatively easily solved with a regular expression. But what if whitespace (sometimes) comes into play ?

Helper.GetIntFromData(packetData
    .Skip(  offset  )
    .Take(  length  )
    .ToArray()  
);

Still doable with a regex, but it's now an unreadable mess of optional whitespace tokens.

OK, but what if the parameters are not always simple identifiers, but arbitrary expressions?

Helper.GetIntFromData(obj.GetData(true).Skip( 7 + GetOffset( item.GetData() ) )
    .Take( length1 / length2 ).ToArray());

This is where regular expressions really break down.

My question is:

Can this be done today? (in a way that keeps you sane, i.e. without regex)

Is there a VS extension or standalone tool that can handle searching and replacing C# code at a higher (semantic) level?

Something that would allow me to search for (I imagine):

Helper.GetIntFromData($expr1.Skip($expr2).Take($expr3).ToArray())

and replace with

Helper.GetIntFromData($1, $2, $3)

Does such a tool exist for C#? (I imagine it could be built around Roslyn.)

like image 880
Cristian Diaconescu Avatar asked Jun 12 '15 07:06

Cristian Diaconescu


People also ask

How do you replace a word in a sentence in C?

int main() { int i, leng; char phrase[DIM], word[DIM], word2[DIM]; printf("Write a sentence\n>>"); fgets(phrase, sizeof(phrase), stdin); printf("Enter the word you want to replace in the sentence\n>> "); fgets(word, sizeof(word), stdin); printf("What do you want to replace it with?\


1 Answers

Resharper has semantic search and replace

Helper.GetIntFromData(packetData.Skip($offset$).Take($length$).ToArray());

with

Helper.GetIntFromData(packetData, $offset$, $length$);

It is white space insensitive and you can constrain the token matches to be of certain types. I use it all the time to do what you are trying to do. I have not yet seen any roslyn based projects that all the user to do this so trivially.

Here is an intro to the feature on resharpers website

http://blog.jetbrains.com/dotnet/2010/04/07/introducing-resharper-50-structural-search-and-replace/

like image 84
bradgonesurfing Avatar answered Oct 04 '22 04:10

bradgonesurfing