Why use anonymous types instead of creating a class

anonymous-types, c#, linq

Solution

Anonymous types are designed to be used from the scope in which they are created. No other scope should ever know about that anonymous type's definition, so since you want to be returning this object from a method, an anonymous type is not appropriate.

In general, the idea is that the object is used in just one or two places, all in the same method, and it's use is so simple and straightforward that there just is no need to create a new named type. They are also immutable, and creating immutable objects in C# is...more verbose.

Problem

I am refactoring an older application, it was using dynamic in-line SQL, pulling data from a large Oracle database. I created a stored procedure (PL/SQL) which works fine. Since it is only one row (datarow) I left it returning a datarow. This class resides in the DAL. As I am refactoring things I thought I would isolate the database (in the DAL) from the business layer (use linQ). My first thought was create an object to contain the returned datarow. One of my coworkers recommended Anonymous types, which I am not familiar with. In the reading I've done so far it looks simple enough. I just don't see the value in it if I have still have to put the fieldnames and field types using the anonymous types. Am I missing something? Would there be more value to using Anonymous types if I was returning a dataset/datatable?

Original source

Related problems