bradgonesurfing
bradgonesurfing

Reputation: 32202

Resharper refactoring pattern to wrap a local variable assignment in try catch

If I have the following code

var x = foo();
DoSomethingWith(x);

where

Foo foo(){...}

sometimes I want to wrap this in an exception handler like so

Foo x;
try{
    x = foo();
}catch(Exception e){
    $InsertPoint$
}
DoSomethingWith(x);

Now I know how to do around templates and I've seen some information on how to do structural pattern matching. Would it be possible in R# to construct a pattern that will get the type of x ( it is declared as var ) and then generate the wrapped form with the explicit declaration.

Upvotes: 2

Views: 181

Answers (1)

John Saunders
John Saunders

Reputation: 161821

Try matching $type$ $id$ = $expr$; and replace with

$type$ $id$;
try{
    $id$ = $expr$;
}catch(Exception e){
   //Insert code here
}

using structured search and replace. It is important to mark $expr$ as an expression not as an identifier

Upvotes: 2

Related Questions