Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C# 4.0 "dynamic" keyword make Generics redundant?

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?

like image 864
andy Avatar asked May 06 '09 06:05

andy


1 Answers

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 some generic operators

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

like image 133
Marc Gravell Avatar answered Oct 09 '22 03:10

Marc Gravell