If the set of property names is the same, then the type will be reused.
class Program
{
static void Main(string[] args)
{
var test = new Test();
var inner = test.Go();
var anonObj = new { Name = "one" };
Console.WriteLine(inner == anonObj.GetType()); // true
}
}
public class Test
{
public Type Go()
{
var anonObj = new { Name = "one" };
return anonObj.GetType();
}
}
So you wouldn't run into problems from multiple calls with the same set of properties. But what about the definitions themselves? I wrote a quick experiment to see what would happen.
class Program
{
static void Main(string[] args)
{
new Test().Go();
Console.WriteLine("End: " + GC.GetTotalMemory(true));
Console.ReadLine();
}
}
public class Test
{
public void Go()
{
var anonObj = new { Name = "one" };
Console.WriteLine(GC.GetTotalMemory(true));
}
}
The memory usage was higher after the anon type was declared, even after all references are gone and garbage collected, so I am assuming that the type definition does stick around after a GC, and thus is around for the life of the AppDomain. So in theory, it could be a problem.
However, it will only create types for unique combinations of properties, so unless this is a very large codebase, it should cause no problems.
Erick