Samvel Siradeghyan
Samvel Siradeghyan

Reputation: 3593

Why methods in DynamicObject class are not generic?

I was reading this article about Dynamic Objects in C# 4.0.
In that example second argument of function TryGetMember(GetMemberBinder binder, out object result) is of type Object. I looked in MSDN and noticed that other methods are getting arguments as Object as well. Why does these functions not generic?
From MSDN

In relation to simple assignments, boxing and unboxing are computationally expensive processes

If boxing/unboxing are expensive wouldn't it be better to use generics?

Thanks.

Upvotes: 3

Views: 346

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503290

Note the "in relation to simple assignments". In other words, compared with one of the cheapest possible operations, boxing is expensive.

Compared with the rest of the machinery involved in dynamic typing, boxing is cheap :)

If TryGetMember were generic, that would mean the caller would have to know what type to expect. One of the points of dynamic typing is that the caller can't guarantee what's going to happen. If I write:

dynamic foo = GetDynamicValueFromSomewhere();
Console.WriteLine(foo.SomeProperty);

that's only going to resolve which overload of Console.WriteLine to use after SomeProperty has been evaluated. It doesn't have an "expected" return type... so what generic type argument would you expect to use?

Bear in mind that most dynamic typing scenarios will use object as the intermediate expression type in the CLR anyway. If I write:

dynamic x = 10;

that's already boxing. You can't represent "an unboxed value type of an indeterminate type" in the CLR. (How much space would it allocate?)

Upvotes: 8

Related Questions