Home > Refactorings > Refactorings for anonymous types

Refactorings for anonymous types

September 27th, 2011

Anonymous types are type declarations that are generated automatically by the compiler without having to explicitly declare it. They provide a convenient way to encapsulate several read-only properties into a single object that is not declared in the code. Anonymous types are supported by C# and Visual Basic programming languages starting from Visual Studio 2008.

After you create an anonymous type object, you can assign it to an implicitly-typed local variable like this:

Refactor! Anonymous type sample code (single type)

The compiler will automatically generate a new class for this anonymous type. If you want to persist it and have a source code of the class, you can automatically convert an anonymous type into a named type by using the Name Anonymous Type refactoring shipped in Refactor! Pro and CodeRush Xpress. This refactoring replaces an anonymous type with a one-to-one class declaration that is generated by the compiler. Additionally, all other anonymous types in this project having the same shape will also be replaced by the new type.

Consider the following code with two anonymous types:

Refactor! Anonymous type sample code (two types)

Applying the Name Anonymous Type:

Refactor! Name Anonymous Type preview

will result in the following class generated, that we immediately rename to “Car” (click the image to enlarge):

Refactor! Name Anonymous Type result type

And creation sides are changed to this:

Refactor! Name Anonymous Type result (creation side)

Now you can declare instances of this class and extend the class as you desire.

There is one more similar refactoring for anonymous types – the Make Explicit (and Name Anonymous Type). In addition to creating a named type declaration that represents an anonymous type, it converts the implicitly-type local variable to a variable with an explicit type, replacing other anonymous types in this project having the same shape by the new type declaration:

Refactor! Make Explicit (and Name Anonymous Type) preview

Don’t forget to review the refactorings for anonymous methods and lambda expressions.

Products: Refactor! Pro, CodeRush Xpress
Versions: 11.1 and up
VS IDEs: any
Updated: Sep/27/2011
ID: R040

Similar Posts: