Anonymous Types In C# Are A Crippled Hack

I’ve been learning a bit of Java recently, reading Unlocking Android and playing with the Android SDK to try and learn how to write apps for my Droid. I have known, intellectually, about some of the key differences between .NET and Java for quite some times now – how Java doesn’t have properties, how events are done through an Observer pattern, and various other differences. Now that I’m trying to put some of these differences in practice, though, I find some of them to be very intriguing – especially the way events are handled.

Most of the sample code that I see with event handling in Android apps look like this:

   1: someButton.setOnClickListener(

   2:     new OnClickListener(){

   3:         public void onClick(View v){

   4:             //do something here to handle the click

   5:         }

   6:     }

   7: );

The setOnClickListener method expects a parameter of type OnClickListener with a method called onClick(View). Rather than declaring this as a full fledged class definition and instantiating it, we are using an anonymous type with inline instantiation. We are new’ing up an OnClickListener class and declaring the methods of the class instance inline with the object initializer.

Now look at what we have to do in C#, by comparison:

   1: public void SomeMethodSomewhere()

   2: {

   3:     someButton.SetOnClickListener(new MyClickListener());

   4: }


   6: public class MyClickListener: OnClickListener

   7: {

   8:     public override void OnClick(View v)

   9:     {

  10:         //handle the click here

  11:     }

  12: }

(Please don’t start complaining about my C# example not using the .NET event system saying that we don’t need anonymous types because we have delegates and multi-cast delegates. I’m well aware of delegates and the .NET eventing system. Honestly, I’m very happy with the .NET eventing system. It works very well and is easy to use. I show this example because it illustrates an apples-to-apples implementation difference between Java and C#.)

The difference may be minor in this small example but it can be rather tedious to have to declare a new class for every single OnClickListener that we want to use. Even if we make OnClickListener an interface, such as IOnClickListener, we will have the same problem and have to declare a new class and implement that interface.

The problem as I see it is that anonymous types in C# are a crippled, lame hack that were only put in place to support the functionality needed for LINQ queries. We can’t declare methods on our anonymous types or instantiate an anonymous type that inherits from anything other than the default Object in C#. This severely limits the capabilities and possibilities of we can do with anonymous types. Honestly, other than ASP.NET MVC Routing declarations and LINQ queries, I have yet to see anyone use an anonymous type in C#.

Dear Microsoft,

Please give us full fledged anonymous types in .NET/C# instead of the crippled hack that was put in place to support LINQ. I would especially love to instantiate an interface as an anonymous type:

   1: public void PleaseLetMeDoThis()

   2: {

   3:     SomeMethod(new ISomeInterface()

   4:     {

   5:         public void DoIt()

   6:         {

   7:             //do something here.

   8:         }

   9:     })

  10: }


  12: public void SomeMethod(ISomeInterface something)

  13: {

  14:     something.DoIt();

  15: }

You’ve given us anonymous methods with delegates. You’ve given us read-only properties in anonymous types. It wouldn’t take that much work to marry the two concepts into a nice syntax like this.



About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs - the amazingly awesome podcast audio hosting service that everyone should be using, and where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, Android, C#, Java. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • It’s interesting reading the reaction of someone from .NET to a useful feature of Java. And, yes, I’ve longed for anonymous classes in C# for a very long time. Imagine the pain that would be taken out of writing stub classes for unit tests if we had this.

  • Ben Hyrman

    Some of my code lately has taken the form

    button.Click += (sender, eventArgs) => { //action here };

    It’s a bit nicer than wiring up to an event handler method.

  • You admit the eventing system was a bad example because there is a better alternative in c#. Can you provide an example of where you are feeling the pain of not having full anonymous types (ie, somwhere that a simple lambda doesn’t suffice)?

    • Marcel Bradea

      There are many. Lambdas are amazing, but as you noted, a simple lambda is just that: simple. A lambda is a single operation, and not a collection of operations grouped together, thus providing no encapsulation of a larger set of responsibility. This is what interfaces provide.

      To have to define a new class only so you can implement an interface is unnecessary extra work, and unfortunately even the event pattern is not the appropriate solution for many situations where you wan’t to ensure a single observer. CocoaTouch (iOS presentation framework written in Objective-C) shows this pattern done really well, where it is used everywhere throughout the framework to ensure that some object can delegate out responsibility to a controlling object. Unlike events or the observer pattern, you never want more than one controlling object to receive the callbacks. This pattern SHOULD be used a lot more throughout C# / WPF to ensure safety and conform to the Spartan Principles, however due to the complexity/effort required to create interfaces in C#, people end up using less appropriate patterns (ie: events, lambdas) in situations where a better solution would be warranted.

      Languages and their limitations shape the APIs and systems we build using them. This is definitely a shortcoming on C#’s part, along with not having optional interface methods, which again forces verbosity and thus creates bad patterns in certain places where much better ones could be used. The only way to implement an interface WITHOUT implementing all its methods in C# is to use an abstract base class with “do nothing” methods, then using composition instead of inheritance in the implementing class to achieve this. Again, C# forces us to EITHER use events/lambdas, in which case there is not concept of mixing multiple operations together, or implement ALL the methods on an interface. The absence of mixins only complicates the matter, since it means that such scenarios can only be implemented through composition, or forwarding all methods on the implementing object to another object that also implements the same interface. Not a pretty set of constraints at all.

  • MM

    “I show this example because it illustrates an apples-to-apples implementation difference between Java and C#.”

    but if i can get all of the nutrition that i need from oranges, why should i care about apples?

    ok that was lame, but the point is, if delegates solve the problem at hand (which i think they do), doesn’t this just become an argument over minor style differences?

  • It’s worth mentioning that you can mimic this Java functionality in F# with Object Expressions:

  • +1 @ Ben Hyrman.

  • Dave

    First: you are wrong, the inline class is meaningless. It is javas way of doing delegates.

    Second: .net 4 have “dynamic”, that lets you do what you want, call methods that the compiler do not know about.

  • @BenHyr – i do that too. like i said, i like the event system in .net. it’s nice. i should have provided a better example of where it would really benefit .net

    @Josh – unit testing w/ manual mock objects (as @Eddy pointed out). the lambda style mocking that we currently have works well, but it gets obtuse really fast. also – object composition, decorator and proxy patterns (no more need to IL weaving to do dynamic proxies) and other scenarios like that.

    @MM – ha! :) events aren’t actually the issue.

    @keith – i’m not surprised that some .net languages support this. after all, it’s just a compiler trick the same way anonymous types are currently done.

    we’re missing out on a lot of possibilities by not having anonymous types. i use delegates every day because they make my life easier. i love having lambda expressions as anonymous delegates. i also really like object initializers so that i don’t have to declare all my properties in 20 different constructors. imagine having all of that wrapped up in one nice syntax that gave us all of those things at once.

    mixins would finally be possible in .net if we could assign methods to our anonymous types, which would give us a great decorator pattern. proxy classes would be so much easier to write and we wouldn’t have to do all that magic IL weaving. and i’m sure there are other possibilities that i’m not thinking off at the moment.

  • I agree 100%. I been saying this for a while now. I even wrote about it here, when I compared C# to Java.

    The very first thing I talk about is this missing feature from C#.

    The uses where it is a good practice are limited, but it is a really good way to unit test legacy code. If you have some very tightly coupled piece of legacy code, and it has some methods that call out to 5 other different concrete classes, you can “skip” that call and return a mock value by making that method protected and anonymously overriding the method in your unit test. It sounds a little weird, but it can be really useful.

    I would especially like to be able to provide a anonymous implementation for an interface. There are many instances I can think of where that would be useful.

    I’m also working on creating apps for my Droid. I found that the development environment is pretty nice, but there is one MAJOR complaint I have. Why the heck did they not make the code generator that generates the R file also generate strongly typed references to the resources? It seems silly to cast out each control or resource value you get to the appropriate type, when it can be inferred and auto-generated.

  • Mike

    After reading this article I came to a lot of the conclusions that others have mentioned. Using delegates for the events (I actually like this better then using a new anonymous class). Using mock objects for testing versus creating our own stubs even if they are anonymous.

    However I really like the potential of what John Sonmez said when he talked about fulfilling an interface. I know that programming to an interface is often preferred and if you took out the capability to re-use a concrete implementation instead of the interface, since the concrete implementation is an anonymous type, other developers would be forced to program to the interface.

  • “mixins would finally be possible in .net if we could assign methods to our anonymous types”

    Yes, except Java doesn’t have that feature either! At least not dynamically. If you look at the feature, Java inner classes are pretty much explicitly designed for implementing events in the absence of delegates. The mixin idea you’re talking about isn’t possible in Java that I know of – do you have an example of what you’d like to see that works Java that doesn’t work in C#?

    If mocking is your specific concern, have you looked at Moles yet? It’s a pretty cool package that works pretty much the way you’re asking.

  • Thomas Eyde

    C# is missing anonymous classes, but Java on the other hand is missing anonymous methods. At least it did when I last checked, which is a long time ago.

    How would the comparison look if you chose to compare lambda expressions in C# with the missing (?) Java feature?

    In my opinion, and totally besides the point, anonymous methods is the better approach. From what I have seen, Java uses anonymous classes when what we really want is a single method.

  • @Thomas Eyde – I’ve used the anonymous inner class in Java for much more than just a single method. I wrote a network protocol in Java and accompanying program to use the protocol that used the anonymous inner classes extensively. Each of these classes had multiple methods and objects.

  • How does this float your boat?

    public class ActionClickListener: OnClickListener
    Action action;
    public ActionClickListener(Action
    _action = action
    public override void OnClick(View v)

  • @Chris / @Thomas – i’m not saying java has everything c# does. never said that, never will. i’m not even going to go down that path because i’m just learning java so i don’t know what all i would want in java

    @harry – hey, now that’s a nice looking work around! i’ve used that type of technique before, but didn’t think about doing in in a situation like this. thanks!

  • MM

    wait, what i am missing here? why are you suddenly OK with a delegate as an alternative?

  • Adam Cooper

    Derick, I agree.

    Our company is doing hybrid .NET and Java development (GWT front-end with a legacy .NET backend), which has given me a unique chance to develop in both languages on a day-to-day basis. While there are a lot of C# niceties I miss when I’m in Java, I really do like Java’s more grown-up version of anonymous classes.

    Like Harry, I tend to pass Action and Func classes a lot when I’m in C#, which is great when all you need to pass is a method or two. But I think a more powerful anonymous class syntax could still be handy in some situations.

    I have yet to hear anyone voice a genuine reason why this would be bad for C#, other than “I don’t like it because C# is better than Java.” As far as I’m concerned, this would be a welcome feature. Nice suggestion.

  • @Harry M -

    THANK YOU! I read this post and my BS meter went off the carts. I immediately cracked open a C# editor to write this very same code. Then I popped back in to post it and caught your reply. Just to complete the code, here’s how the author would use your class with an inline method:

    OnClickListener ocl = new ActionClickListener(
    delegate(View v) {
    // do whatever I want to here
    // Console.WriteLine(“delegate”);

    This is exactly how this problem should be handled in C#. I think the author wanted to rant about Java and Microsoft rather than just asking a simple question of any experienced C# dev.

  • Michael Chandler

    Clearly this is a necessary idiom within Java as they don’t support delegates. I’ve been working with .NET for the past 3 years and have never felt the need to use ‘anonymous inner classes’.

    A few of the comments mention testing as a candidate of this. I partly agree — but why not use a good isolation framework instead?

    As others have said, are you able to give some concrete examples on when you would use this?

  • As lots of other people have mentioned, the eventing example is unfortunate. There is a real missing piece of functionality from C# here, though – that is totally correct. Lambda expressions and delegates solve the one-function problem, but the real trouble is handling the case where you want to send something in with more than one method, or something that has both state and a method. This is powerful and used a lot in Java (not only for events). In those circumstances I’ve found myself using an API where I send in several delegates/lambdas that all take a self as an explicit argument. Ugly, but useful.

  • @MM – there’s a difference between accepting a workaround and wanting a solution, and they are not in conflict with each other. just because i want full anonymous types doesn’t mean i won’t use a workaround.

    @John Sonmez and @Adam Cooper – thanks! glad i’m not alone. :)

    @matmc3 – thanks for putting words in my mouth and assuming you know why i’m posting this! i’m a full time C# developer. have been doing .NET for 8 years, but i obviously just want to bash on the company that makes such a great platform. and it’s obviously better to be a fanboy and assume that microsoft is product perfection rather than questioning why a useful feature is missing and show some use cases for it. nice one. you got me.

    @Michael Chandler,

    proxy classes… i really want this for proxy classes.

    I don’t have the luxury of using Castle.DynamicProxy and it’s IL weaving in the Compact Framework. If I had a full featured anonymous type, I would have been able to make better use of the proxy classes I had to create by hand without polluting my solution with dozens of copies of the workaround that Harry M posted.

    as it stands, I used the solution that Harry M posted and was very happy to have see his reply and to be able to use it. it is an acceptable way of handling the proxy classes that I need since we don’t have full anonymous types. i’m just annoyed that i need to create one instance of this solution for every proxy that I need, so that i can inject them into my dependencies via my IoC container. but hey, at least its a working solution!

    @Harry M. – your suggestion is indeed very useful. thanks again. :)

  • @mattmc3

    While your code is an example of using C# to write equivalent code. It still is not quite the same thing you can do with anonymous overrides in Java. (Don’t get me wrong here. I prefer C# to Java, but working in both, I have learned to appreciate the pros of each.)

    In Java you can do something like this….

    ComplicatedClass class = new ComplicatedClass()
    protected void hitTheDataBase()
    // do nothing, want to mock this call out.

    protected int pickARandomNumber()
    return 2; // I like two, it doesn’t get enough credit.

    You can also create an anonymous static block, which is actually kind of scary, but JMock uses it for making it real easy to set up recording.

    Don’t get me wrong. Java needs real delegates… But it does have this pretty cool feature.

  • Full anonymous classes would be awesome in C#! Will have to play with 4.0 and see whats possible with dynamic. This is the first Java feature that I’ve seen that is superior to C#.

  • AviS

    Sorry (and maybe i’m missing the whole point here), but to me it looks like Java’s implementation is a crippled hack for anonymous methods (not to mention the lack of lambda expressions). Functional programming is all about the functions, and that is so easy and elegant in C#. Defining inline stuff (classes or methods) should be very readable since, well, it’s defined inline. And I think inline methods are much more readable than inline classes.

  • @AviS – i agree that java is missing delegates (anonymous methods). wrong perspective for this post, though. i’m looking at c# from a java lens, not java from a c# lens.

  • James


    Depressing that so many people miss the point. You cannot do a method-inline implementation in C#. You can in Java.

    Some times, for interfaces with 2 or 3 methods, it would be real handy to be able to implement it inline in C#. But you can’t. You can in Java.

    Support for delegates is not the same thing.

    Can you implement an interface inline in C#? No, you can’t. But in Java you can.

    Got that?


    (9-year MS developer, but that doesn’t cause me to turn off my brain).

  • Esteban

    Sometimes when you’ve stated a dependency on an interface but really only depended on a single method’s declaration from that interface, you probably exaggerated your needs.

    Got that?

    Of course, as a consumer of such a stupid class, the functionality you suggest is desperately wanted.

    By the way, why are you so angry?

  • MM


    My neighbor and I both drive compact cars. The other day we were standing outside and someone drove by in a big van. My neighbor started lamenting about how he wished he had a big van. So I said to my neighbor, “Neighbor, the only thing I’ve ever seen you use your compact car for is driving yourself, and only yourself, to work. Why would you need a big van?”

    Please note that I did not ask him to explain the difference between a compact car and a big van.

  • @MM

    I own two compact cars (one for me, one for my wife). I have to rent a truck every time I want to buy anything larger than half a cubic meter. what you’re saying is that i shouldn’t wish my car was bigger when i need to buy something that won’t fit in it… that i shouldn’t want to a bigger vehicle so that i can be larger things.

    you’ve only ever seen your neighbor drive himself to work… is that because that’s all he ever does? or is that because that’s all his car will let him do? perhaps there are times when your neighbor really needed a large van, but only had a compact car and therefore was only able to drive to work instead of being able to do all the things a large van would let them do.

    … don’t confuse “can’t” with “don’t need to”.

  • MM


    no, no, no. that’s not what i’m saying at all. i’m saying what you’re saying. i don’t think anyone was unclear on the difference between the language constructs. we were unclear on what problem it was trying to solve. i actually chose the word “seen” very deliberately in my post above. because that gets right to the point. the question we were all asking is “why do you want this thing?” not “what is this thing that you want?”

    hope that clears it up (it made so much sense in my head). sorry for the confusion

  • @MM – ok, yeah. it was the word “seen” that sparked that response. i see your point now.

  • I think the conclusion here is, F# ftw. That said, while you can’t do interface or class instantiation, you can mimic anonymous methods within anonymous types by using delegate properties. Yes, I know that’s still not the same, but it gets you closer.

    With the Reactive Extensions release, I see more people wanting to move to the Observable pattern, and that will likely have us wanting a lot of these features in C#.

    • Gusman_Bjork

              void CreateDinaClass()

                  var dinaclass = new

                      DoThis = new Func(s => int.Parse(s)),
                      DoThat = new Func
                          ((a, b) => 
                                  if(a  45)
                                      System.Windows.Forms.MessageBox.Show(“Oh god!!!!”);

                                  return a + b;




              void UseDinaClass(dynamic AnonClass)

      So, doesn’t this works like a Java anonymous class?There’s no need for an interface with the dynamic keyword and witha multiline lambda expression a function can be created.I know it’s an old post but I wanted to show this way of creatinganonymous classes with a very similar functionality to Java anonymousclasses.I hate the anonymous classes in Java, i had to program during two yearswith it and really hated the inner classes. And that’s not because C#doesn’t have them, it’s because the readability of the code gets killed.In a function where you hook to multiple events, the code becomes a truly mess which nobody can read without struggling his brain.

  • dan

    I’ve coded much in both C# and Java, and I really prefer Java’s anonymous classes. They’re much more powerful, they allow you to have clearly defined shared data between methods of a protocol unlike the “closures everywhere” and “a separate decoupled delegate class for each little action” hack of C#. Say I need to load data from disk in a separate thread and then “finalize/complete” it in another thread (the underlying library is thread-unsafe). In Java I create an abstract class with two abstract methods “executeAsync” and “complete”. Then I can create an anonymous class where method “executeAsync” stores its results inside a shared field, which “complete” later picks on. In C# I would need to create two absolutely separate delegate types, then instantiate two delegates, and the only data they can sure are closured method variables, which is pretty dangerous because C# doesn’t have a “final” constraint on closures like in Java and there can be data mismatch if you change the variable somewhere. Bugs, bugs everywhere. But of course for simple GUI, C#’s delegates are good. The funny thing is that delegate-based GUI programming is outdated and they’re moving to declarative WPF etc. now, so C#’s delegates aren’t that needed anymore.

  • Yes, we need full fledged anonymous types

  • Anon

    .NET supports this using Func and/or Action delegates, which, in my opinion, are much easier to grock. I don’t need a new instance of ISomeInterface because it only has one method, why not just pass the method definition (delegate, lambda)

  • Jon Davis

    This is a 3 1/2 years old rant but FYI yes you can declare a method as a member of an anonymous type. Technically it would be a typed delegate property. Example:

    var myObj = new {
    MyFunction = (Func) () => {
    return “Hello”;

    var execute_result = myObj.MyFunction();

    I might have that syntax a bit wrong, I’m not typing this in an IDE with a compiler, but you get the idea.