tags:

views:

62

answers:

4

Can I define an object-structure as a parameter to a method in the parameter declaration without having to create a type?

I am inspired by LINQ to SQL queries, where you are able to return a subset of your query-results in the form of a new object:

var query = from t in dc.Table select new { Foo = t.column };
+1  A: 

Nope, you cannot declare an anonymous type as an input parameter, and you cannot return it, unless you return it as an object. See this blog post for a hacky workaround, if you want, but that's really still just boxing and unboxing the type back and forth, so it's not actually better than just treating it as an object.

David Hedlund
+1  A: 

What you're describing isn't possible. In the case of your Linq to Sql query, the C# compiler creates an anonymous type with a single property named Foo with the same type as t.column. Type inferencing is then used and the variable "query" is actually strongly typed to this anonymous type (which is what gives you intellisense goodness on this variable).

Using "var" as a parameter type isn't possible because the type of the parameter can't be inferred, it requires the calling expression to decide on the actual type of the parameter.

The best that you could do would be to use generics and iterate through properties:

public static void Print<T>(T obj)
{
    Type type = typeof(T);
    PropertyInfo[] properties = type.GetProperties();
    foreach(PropertyInfo pi in properties)
    {
        Console.WriteLine(pi.Name + ": " + pi.GetValue(obj, null));
    }
}

which gives you a "rudimentary" ability to use anonymous types (or any type for that matter) as a parameter.

LorenVS
A: 

How useful is a parameter to a function that you can't use directly? Function parameters should help document the function.

eburley