views:

1200

answers:

5

hey guys,

I'm very excited about the dynamic features in C# (C#4 dynamic keyword - why not?), especially because in certain Library parts of my code I use a lot of reflection.

My question is twofold:

1. does "dynamic" replace Generics, as in the case below?

Generics method:

public static void Do_Something_If_Object_Not_Null<SomeType>(SomeType ObjToTest) {

        //test object is not null, regardless of its Type
        if (!EqualityComparer<SomeType>.Default.Equals(ObjToTest, default(SomeType))) {
            //do something
        }
    }

dynamic method(??):

public static void Do_Something_If_Object_Not_Null(dynamic ObjToTest) {

        //test object is not null, regardless of its Type?? but how?
        if (ObjToTest != null) {
            //do something
        }
    }

2. does "dynamic" now allow for methods to return Anonymous types, as in the case below?:

 public static List<dynamic> ReturnAnonymousType() {
        return MyDataContext.SomeEntities.Entity.Select(e => e.Property1, e.Property2).ToList();
    }

cool, cheers

EDIT:

Having thought through my question a little more, and in light of the answers, I see I completely messed up the main generic/dynamic question. They are indeed completely different. So yeah, thanks for all the info.

What about point 2 though?

+6  A: 

To answer your first question, generics are resolved compile time, dynamic types at runtime. So there is a definite difference in type safety and speed.

Peter van der Heijden
For completeness, generics in .NET are provided by the runtime, and you can specify generic type arguments at runtime if you need.
Marc Gravell
@Peter: thanks peter. I was thinking more in terms of implementation. Though i see now that actually using "dynamic" instead of Generics, as my example, would be kinda like using Object
andy
+6  A: 

Dynamic classes and Generics are completely different concepts. With generics you define types at compile time. They don't change, they are not dynamic. You just put a "placeholder" to some class or method to make the calling code define the type.

Dynamic methods are defined at runtime. You don't have compile-time type safety there. The dynamic class is similar as if you have object references and call methods by its string names using reflection.

Stefan Steinegger
+1  A: 

Answer to the second question: You can return anonymous types in C# 3.0. Cast the type to object, return it and use reflection to access it's members. The dynamic keyword is just syntactic sugar for that.

Niki
thanks niki. so, in C#4.0, could I return dynamic instead of object and then not have to use reflection?
andy
+8  A: 

To answer your question. No.

  • Generics gives you "algorithm reuse" - you write code independent of a data Type. the dynamic keyword doesn't do anything related to this. I define List<T> and then i can use it for List of strings, ints, etc...
  • Type safety: The whole compile time checking debate. Dynamic variables will not alert you with compile time warnings/errors in case you make a mistake they will just blow up at runtime if the method you attempt to invoke is missing. Static vs Dynamic typing debate
  • Performance : Generics improves the performance for algorithms/code using Value types by a significant order of magnitude. It prevents the whole boxing-unboxing cycle that cost us pre-Generics. Dynamic doesn't do anything for this too.

What the dynamic keyword would give you is

  • simpler code (when you are interoperating with Excel lets say..) You don't need to specify the name of the classes or the object model. If you invoke the right methods, the runtime will take care of invoking that method if it exists in the object at that time. The compiler lets you get away even if the method is not defined. However it implies that this will be slower than making a compiler-verified/static-typed method call since the CLR would have to perform checks before making a dynamic var field/method invoke.
  • The dynamic variable can hold different types of objects at different points of time - You're not bound to a specific family or type of objects.
Gishu
thanks Gishu, great answer. It was 50/50 between you and Marc. SO should really allow more than one answer right?...go figure. thanks again
andy
+8  A: 

dynamic might simplify a limited number of reflection scenarios (where you know the member-name up front, but there is no interface) - in particular, it might help with generic operators (although other answers exist) - but other than the generic operators trick, there is little crossover with generics.

Generics allow you to know (at compile time) about the type you are working with - conversely, dynamic doesn't care about the type. In particular - generics allow you to specify and prove a number of conditions about a type - i.e. it might implement some interface, or have a public parameterless constructor. dynamic doesn't help with either: it doesn't support interfaces, and worse than simply not caring about interfaces, it means that we can't even see explicit interface implementations with dynamic.

Additionally, dynamic is really a special case of object, so boxing comes into play, but with a vengence.

In reality, you should limit your use of dynamic to a few cases:

  • COM interop
  • DLR interop
  • maybe some light duck typing
  • maybe smoe generic operators

For all other cases, generics and regular C# are the way to go.

Marc Gravell