Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c# - Difference between Object, Dynamic and Var

I need to know the difference between these three keywords Object , Dynamic and var in C#.

I have seen this link but i don't understand in which case i have to use each one.

Can you explain for me, please, the difference between these keywords ? What are the utilities of each keyword?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object:

Each object in C# is derived from object type, either directly or indirectly. It is compile time variable and require boxing and unboxing for conversion and it makes it slow. You can change value type to reference type and vice versa.

public void CheckObject()
{
    object test = 10;
    test = test + 10;    // Compile time error
    test = "hello";      // No error, Boxing happens here
}

Var:

It is compile time variable and does not require boxing and unboxing. Since Var is a compile time feature, all type checking is done at compile time only. Once Var has been initialized, you can't change type stored in it.

public void CheckVar()
{
    var test = 10;         // after this line test has become of integer type
    test = test + 10;      // No error
    test = "hello";        // Compile time error as test is an integer type
}

Dynamic:

It is run time variable and not require boxing and unboxing. You can assign and value to dynamic and also can change value type stored in same. All errors on dynamic can be discovered at run time only. We can also say that dynamic is a run time object which can hold any type of data.

public void CheckDynamic()
{
    dynamic test = 10;
    test = test + 10;     // No error
    test = "hello";       // No error, neither compile time nor run time
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...