.NET Framework - Perils and Merits of Anonymous classes? Anonymous Descendant class

Asked By SiegfriedHeintz
22-Feb-08 09:19 PM
Can someone help me understand the perils and merits of anonymous classes in
C# 3.0?

Would anonymous classes be most useful when used with reflection? I cannot
figure out how else I would pass them to a function.

How useful is a type if we never pass its instances to a function?

If we do pass an instance of an anonymouse type to a function, can we do
anything with it without using reflection?

The answer to that question might be yes if we can specify an ancestor.
Unfortunately, Andrew Troelsen's book did not show how to create anonymouse
descendant classes.

If I have a class Child, can I create an anonymouse descendant class that
represents a parent that has multiple offspring stored in a linked list and
pass this to a function expecting an instance of class child? Can someone
give me some sample code to do this?

Thanks,
Siegfried
LINQ
(1)
IEnumerable
(1)
Descendant
(1)
DataSource
(1)
TParent
(1)
TChild
(1)
ChildSelector
(1)
Merits
(1)
  Nicholas Paldino [.NET/C# MVP] replied...
23-Feb-08 12:03 AM
Siegfried,

Anonymous types are not meant to be passed outside of the
method/property that they are declared in.  The scope is limited to that
method.  You ^could^ use reflection, but it's really not worth it, you might
as well define your own class at that point and simplify your code.

It's useful because you can create little utility types to aid you in
the operations in that method/property, create projections in queries.

For your specific example, you have to create a concrete Parent type and
have properties that expose the children, then create an instance of that
type and populate the data.  This is if you want to use it across different
methods/properties.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
  Jon Skeet [C# MVP] replied...
23-Feb-08 02:34 AM
Well, except to generic methods. That's a very important exception,
because otherwise they really would be useless.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
  Marc Gravell replied...
24-Feb-08 08:58 AM
It is my guess that they will also have a use for (read-only) views on
data - i.e. get your custom projection into an array/list, and use
that as a DataSource for a list/grid/etc. An indirect reflection
usage...

Maybe ;-p
  Marc Gravell replied...
24-Feb-08 08:58 AM
Not directly - but in many cases the common approach is to express the
relationship via a delegate - for example (perhaps; I'm just
speculating here...) something like:

public static void Foo<TParent, TChild>(this IEnumerable<TParent>
parents, Func<TParent, IEnumerable<TChild>> childSelector) {
foreach(TParent parent in parents) {
// do something with parent...
foreach(TChild child in childSelector(parent)) {
// do something with child
}
}
}

You could then call with something *roughly* like:

var orders = {LINQ query}
orders.Foo(x=>x.Lines); // shows the lines per order...

The "real" approach would of course depend on your exact needs... and
ensuring that the compiler can use inference on the API is sometimes
another black art... (but *much* better in C# 3 than C# 2 due to the
inference changes).

Marc
  Nicholas Paldino [.NET/C# MVP] replied...
23-Feb-08 09:48 AM
I should elaborate.  Anonymous classes are not intended to be used
^directly^ outside of the method they are declared in.  So yes, you can pass
them to generic methods (how else would LINQ work), but you can't access
anything meaningful on them, as they won't satisfy any constraint except the
new constraint.  You just have the reference which is passed along in some
way.


--
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
  Siegfried Heintze replied...
23-Feb-08 10:50 PM
Can I conclude from the above that it is not possible to create an anonymous
descendant class (except for descendants of Object)?
Thanks,
Siegfried
Create New Account
help
they're great - when used appropriately. They can greatly enhance the readability of code, and LINQ is a great example. Which do you think is clearer: 1) Without extension methods: IEnumerable<string> names = Enumerable.Select( (Enumerable.Where(people, person = > person.Age > 17), person = > person.Name); or IEnumerable<string> names = people.Where(person = > person.Age > 17) .Select(person = > person.Name); ? The latter gives abused. However, they allow a lot of really *nice* uses too - and enriching interfaces (as LINQ does) is probably the best use going. Of course, you can avoid using them yourself merely your opinion. Many people can and do disagree. One particular example: much of what LINQ provides would not work without extension methods. It relies on it heavily. But regardless, no of OO. Second, extension methods are the least kludgy way to work with objects in LINQ. Without extensions methods, LINQ would be both verbose and rather neutered. Used incorrectly, extension methods become a major cluster Methods? As far as I can see, a generic could have done the trick here: Linq<People> people; IEnumerable<string> names = 3D people.Where(person = 3D> person.Age > 17) .Select(person
source, and I have had very positive experiences of its Java cousin. As for Microsoft: LINQ to SQL will be released with .NET 3.5, but that only works with SQL will wait until ADO.NET 3 is released with SQL Server 2008, and with it LINQ to Entities. Whichever you choose, don't underestimate the importance of LINQ. Even if you don't plan to use C# 3 yet, you're likely to in the future, and LINQ is *lovely* where you can use it. (In some cases you may have a query which can't be expressed in LINQ, but that's okay.) As for backward compatibility: I wouldn't expect MS to release problems, and which is also why we didn't use this pattern in LLBLGen Pro. Linq to Sql / Entities both have the same attach / detach hell btw. FB - - - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Lead developer of claim to be an expert in ORM in general. (As another couple of data points, LINQ to SQL has the same session bias, and I believe that the ADO.NET Entity That's also why they have teh add / detach hell already looming on the horizon (Linq to sql will throw exceptions in these cases when attaching graphs) and together with deferred
NET Framework Is Linq to SQL any good? I am a big fan of linq but in my opinion linq to sql is a complete waste of time. Why on earth take something that is difficult to write by creating a translation layer. I see people here struggling to write linq to sql queries. It also creates the problem of being locked into a particular product in newsgroups on those who disagree reply. :-) Thanks in advance, Michael If we ignore the LINQ to SQL vs LINQ to EF aspect. You should use LINQ to EF not LINQ to SQL. .NET wanted an ORM. Many people including me like ORM's for certain
NET Framework Are Linq-SQL methods commutative Are Linq-SQL methods commutative ? Should the following queries return same or different results ? var query = query the same on each of them (because Skip and Take make no sense without ordering, LINQ to SQL will create an order for you, which irritates me to no end, but know what rows will be returned. I tried it out to be sure, and indeed Linq to Sql generates two different queries (which really hurt my eyes but that's another I do understand the order, but it's a bit strange as well. For example, Linq apparently has no problem with an Order by placed in front of a where, however limit and offset clauses does not matter. So when moving from PostgreSQL direct SQL to Linq-PostgreSQL this is not intuitive. The major issue is that I have no idea how and Take() effectively (so that minimal possible number of rows are returned from server) in Linq-PostgreSQL driver. In standard SQL Postgres uses LIMIT and OFFSET are orthogonal and there is difficulties? Jon Frans, See inline: Not really, because to translate what is being done in LINQ to database land, you would actually perform a query on the result set of the