30 April 2007

Format Strings -- Episode Two

Last time I wrote about using string.Format as you type. What if you already have some code and want to transform it to string.Format?

    public override string ToString()
    {
      return "Folder: '" + myPath + "'";
    }

When you position caret inside such string expression, ReSharper displays light bulb and suggests few context actions (caret was on myPath in this case):



It is not surprizing that the first item in menu does what we want:

    public override string ToString()
    {
      return string.Format("Folder: '{0}'", myPath);
    }

If there is known method overload that fits format style, it will be used instead of creating extra string.Format call:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '" + myPath + "'");
    }

ReSharper converts it to:

    public void Write(StreamWriter writer)
    {
      writer.Write("Folder: '{0}'", myPath);
    }


Note: Some or all of the features mentioned in this article may be available only in latest EAP versions of ReSharper.

2 comments:

Anonymous said...

How can we modify the code that ReSharper creates when we use a Context Menu option i.e. check if parameter is null?
Quite keen to reformat the output

Resharper spits out:

if (systemRepository == null) throw new ArgumentNullException("systemRepository");

but I want it to spit out:

if (systemRepository == null)
{
throw new ArgumentNullException("systemRepository");
}

Cheers!

Ilya Ryzhenkov said...

You just need to setup formatting options. Open Options / Languages / C# / Formatting Style / Braces Layout, then set "Braces in if-else statement" to "Add".