I have a function that returns an object that represents a record in my database plus additional columns. Instead of creating a separate class for this object I was wondering if there is another way, for example:
public object GetRecord(string key)
{
var item = select new {column1, column2};
return item;
}
public void main()
{
var item = GetRecord(1);
// I want to be able to reference column1 on item.
var x = item.column1;
}
Yes, there are other ways (quite a few actually), but I strongly suggest you not use any of them. The best option for handling this case is to create a new custom type that holds onto the data that you have. It will by far be the most maintainable option.
Anonymous types were designed specifically to be used within the scope of a single method. You’re fighting the design of the functionality to do otherwise, and so it will be difficult to do, you’ll most likely lose Intellisense, performance will most likely suffer, and the poor sap that needs to come back and maintain the code will have no idea what’s going on or how to adjust the query.
The primary problem with most of the alternate solutions is that you lose compile time checking. If the query removes a parameter, adds a parameter, change a type, etc. the code that uses it has no way of knowing. When writing code to use a query you have no way of knowing what all of the pieces of data are, what their types are, what the names of the variables are, etc. You need to worry about typos in variable names that the compiler can’t catch, and you’ll consistently need to be looking at the internal workings of the method that generates the query. You lose the ability to treat it as a black box or abstraction, which is significant.
If you’re worried about the time and effort it would take to create these custom types, there are a number of automated tools out there designed for generating such classes based on database tables or other sources.