Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dynamic is same as Object

Tags:

c#

asp.net

In "CLR via C#" book it's mentioned that dynamic keyword corresponding FCL type is System.Object. please clarify this .

like image 793
Saokat Ali Avatar asked Mar 10 '26 00:03

Saokat Ali


2 Answers

It's not the same thing from the C#'s point of view at all... but in the compiled code, a variable declared as type dynamic will usually (possibly always) correspond with a CLR field or local variable of type object.

The C# compiler is responsible for making sure that any source code using that value has the dynamic behaviour applied to it. object is simply the compiler the representation uses for storage. It also applies the [Dynamic] attribute where appropriate, so that other code knows it's to be treated dynamically.

For example, consider this:

public class Foo
{
    public dynamic someField;
}

I believe that will be compiled into IL equivalent to:

public class Foo
{
    [Dynamic]
    public object someField;
}

now if you write:

Foo foo = new Foo();
foo.someField = "hello";
Console.WriteLine(foo.someField.Length);

the compiler uses the attribute to know that foo.someField is dynamic, so the Length property should be dynamically bound.

like image 104
Jon Skeet Avatar answered Mar 12 '26 14:03

Jon Skeet


From MSDN:

The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object.

And:

Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.

(emphasis mine)

Since a dynamic reference needs to be able to take any type, it is in effect of the type object (or at least to all appearances and uses), but the compiler will not perform certain type checks on it.

like image 43
Oded Avatar answered Mar 12 '26 14:03

Oded