Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating classes from Anonymous types in C# [closed]

Are there any tools that can generate classes from anonymous types?

I have a complex data structure that I have created using anonymous types. I would like to use this data structure in other places where the anonymous type would be out of scope. That's why I'm looking for such a code generation tool.

like image 247
Ronnie Overby Avatar asked Sep 06 '25 12:09

Ronnie Overby


2 Answers

I found another way that will do this without using Resharper. It is tested on VS 2015.

Suppose you have an anonymous type like this:

return new
{
    Prop = "val"
};

Just give it a name, like this

return new AnonType
{
    Prop = "val"
};

and after that a light bulb appears near the first line and when you click it, it shows you options that will generate this class for you, wherever you want.

Here you can see what I'm talking about.

Demonstration

like image 79
Ahmad Avatar answered Sep 08 '25 20:09

Ahmad


That's one of the refactorings supported by Resharper. With nested anonymous types (where one anonymous type has properties of another anonymous type), you'll just have to convert the inner types before you get the option to convert the outer one.

like image 21
Jonathan Rupp Avatar answered Sep 08 '25 20:09

Jonathan Rupp