5

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?

gunr2171
  • 16,104
  • 25
  • 61
  • 88
gDeveloper
  • 61
  • 1
  • 3
  • It's a case-by-case basis. If you need to pass data between functions, you can't use them. – gunr2171 Jan 29 '14 at 21:36
  • Thank you for all for the answers. Sounds like anonymous types are not the way to go and I should stick with using a class. – gDeveloper Jan 30 '14 at 13:30

3 Answers3

9

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 1
    [With C# 7, we can now return Tuples which can be reassigned to an anonymous type.](https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/) – Nicholas Miller Nov 16 '17 at 15:49
  • yes but in LINQ queries , anonymous types are the best solution. –  Oct 24 '18 at 09:06
1

Anonymous types are great for one-time operations, but I wouldn't use them as a substitute for db entities. It's really a bad design to use them like that.

walther
  • 13,466
  • 5
  • 41
  • 67
0

Since you cannot return anonymous types, you certainly should not use then to represent domain objects. Their advantage comes in the form of one time uses, usually inside lambda expressions while processing a collections of data objects.

A typical example is when you need to process two separate collections: you can zip them together, and project the result over an anonymous type that only exists within the scope of the LINQ query.

rae1
  • 6,066
  • 4
  • 27
  • 48