IT

동적 (C # 4)과 var의 차이점은 무엇입니까?

lottoking 2020. 5. 12. 08:11
반응형

동적 (C # 4)과 var의 차이점은 무엇입니까?


C # v4와 함께 제공되는 새 키워드에 대한 기사를 많이 읽었지만 "동적"과 "var"의 차이점을 알 수 없었습니다.

이 기사 는 그것에 대해 생각하게 만들었지 만 여전히 차이점을 볼 수는 없습니다.

"var"을 로컬 변수로만 사용할 수 있고 로컬 및 글로벌 모두로 동적으로 사용할 수 있습니까?

동적 키워드없이 일부 코드를 표시 한 다음 동적 키워드로 동일한 코드를 표시 할 수 있습니까?


var정적 유형입니다-컴파일러와 런타임 은 유형을 알고 있습니다 -입력을 저장하면됩니다 ... 다음은 100 % 동일합니다.

var s = "abc";
Console.WriteLine(s.Length);

string s = "abc";
Console.WriteLine(s.Length);

일어난 모두는 것이 었습니다 컴파일러는 것을 알아 냈 s(이니셜)에서 문자열이어야합니다. 두 경우 모두 (IL) s.Length에서 (인스턴스) string.Length속성 의미합니다 .

dynamicA는 매우 다른 짐승; 와 가장 유사 object하지만 동적 디스패치가 있습니다.

dynamic s = "abc";
Console.WriteLine(s.Length);

여기에 dynamics 으로 입력 됩니다 . 그것에 대해 알지 못한다 string.Length는 모르기 때문에, 아무것도 에 대한 s컴파일 타임에 있습니다. 예를 들어 다음은 컴파일되지만 실행되지는 않습니다.

dynamic s = "abc";
Console.WriteLine(s.FlibbleBananaSnowball);

런타임 (전용), 그것은 것입니다 확인 에 대한 FlibbleBananaSnowball재산 - 그것을 찾기 위해 실패, 그리고 불꽃의 샤워에서 폭발.

을 사용 dynamic하면 속성 / 메소드 / 연산자 / 등이 실제 객체를 기반으로 런타임에 해결 됩니다 . COM (런타임 전용 속성을 가질 수 있음), DLR 또는와 같은 다른 동적 시스템과 대화 할 때 매우 편리합니다 javascript.


var선언 된 변수 는 내재적이지만 정적으로 유형이 지정됩니다. dynamic 으로 선언 된 변수 는 동적으로 유형이 지정됩니다. 이 기능은 Ruby 및 Python과 같은 동적 언어를 지원하기 위해 CLR에 추가되었습니다.

나는이 수단 것을 추가해야 동적 선언이 실행 시간에 해결이 VAR의 선언은 컴파일 시간에 해결됩니다.


dynamicvar의 차이점을 설명하려고합니다 .

dynamic d1;
d1 = 1;
d1 = "http://mycodelogic.com";

작동합니다. 컴파일러는 동적 변수 유형을 다시 만들 수 있습니다 .
먼저 형식을 정수 로 만들고 그 후에 컴파일러는 형식을 문자열 로 다시
만들지 만 var의 경우

var v1;  // Compiler will throw error because we have to initialized at the time of declaration  
var v2 = 1; // Compiler will create v1 as **integer**
v2 = "Suneel Gupta"; // Compiler will throw error because, compiler will not recreate the type of variable 


' var '키워드를 사용하는 경우 컴파일 타임에 컴파일러에서 유형이 결정되는 반면 ' dynamic '키워드를 사용하는 경우 런타임에 의해 유형이 결정됩니다.
' var '키워드는 컴파일러가 초기화 표현식에서 유형을 판별 할 수있는 암시 적으로 유형이 지정된 로컬 변수입니다. LINQ 프로그래밍을 수행 할 때 매우 유용합니다.
컴파일러에는 동적 유형의 변수 에 대한 정보가 없습니다 . 따라서 컴파일러는 지능을 보여주지 않습니다.
컴파일러에는 var 유형 의 저장된 값에 대한 모든 정보가 있으므로 컴파일러는 지능을 보여줍니다. 동적
type은 함수 인수로 전달 될 수 있고 function은 객체 유형을 반환 할 수
있지만
var type은 함수 인수로 전달 될 수 없으며 함수는 객체 유형을 반환 할 수 없습니다. 이 유형의 변수는 정의 된 범위에서 작동 할 수 있습니다.


var는 정적 형식 검사 (초기 바인딩)가 적용되었음을 나타냅니다. dynamic은 동적 유형 검사 (후기 바인딩)가 적용됨을 의미합니다. 코드 측면에서 다음을 고려하십시오.

class Junk
{
    public void Hello()
    {
        Console.WriteLine("Hello");
    }
}

class Program
{
    static void Main(String[] args)
    {
        var a = new Junk();
        dynamic b = new Junk();

        a.Hello();

        b.Hello();
    }
}

이것을 컴파일하고 ILSpy로 결과를 검사하면 컴파일러가 b에서 Hello ()에 대한 호출을 처리하는 늦은 바인딩 코드를 추가 한 반면 초기 바인딩이 a에 적용되었으므로 a는 Hello를 호출 할 수 있음을 알 수 있습니다 () 직접.

예 (ILSpy 분해)

using System;
namespace ConsoleApplication1
{
    internal class Junk
    {
        public void Hello()
        {
            Console.WriteLine("Hello");
        }
    }
}

using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Runtime.CompilerServices;
namespace ConsoleApplication1
{
    internal class Program
    {
        [CompilerGenerated]
        private static class <Main>o__SiteContainer0
        {
            public static CallSite<Action<CallSite, object>> <>p__Site1;
        }
        private static void Main(string[] args)
        {
            Junk a = new Junk();      //NOTE: Compiler converted var to Junk
            object b = new Junk();    //NOTE: Compiler converted dynamic to object
            a.Hello();  //Already Junk so just call the method.

                          //NOTE: Runtime binding (late binding) implementation added by compiler.
            if (Program.<Main>o__SiteContainer0.<>p__Site1 == null)
            {
                Program.<Main>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, object>>.Create(Binder.InvokeMember(CSharpBinderFlags.ResultDiscarded, "Hello", null, typeof(Program), new CSharpArgumentInfo[]
                {
                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
                }));
            }
            Program.<Main>o__SiteContainer0.<>p__Site1.Target(Program.<Main>o__SiteContainer0.<>p__Site1, b);
        }
    }
}

The best thing you can do to discover the difference is to write yourself a little console app like this one, and test it yourself with ILSpy.


One big difference - you can have a dynamic return type.

dynamic Foo(int x)
{
    dynamic result;

    if (x < 5)
      result = x;
    else
      result = x.ToString();

    return result;
}

Here is simple example which demonstrates difference between Dynamic (4.0) and Var

dynamic  di = 20;
dynamic ds = "sadlfk";
var vi = 10;
var vsTemp= "sdklf";

Console.WriteLine(di.GetType().ToString());          //Prints System.Int32
Console.WriteLine(ds.GetType().ToString());          //Prints System.String
Console.WriteLine(vi.GetType().ToString());          //Prints System.Int32
Console.WriteLine(vsTemp.GetType().ToString());      //Prints System.String

**ds = 12;**   //ds is treated as string until this stmt now assigning integer.

Console.WriteLine(ds.GetType().ToString());          **//Prints System.Int32**

**vs = 12**; //*Gives compile time error* - Here is the difference between Var and Dynamic. var is compile time bound variable.

Shiva Mamidi


var is just a shorthand for a normal type declaration, where you let the compiler guess the correct type.

dynamic is a new (static) type, where all checks are done at runtime, not by the compiler.


The type of a variable declared with var is determined by the compiler, it is a shortcut to specifying the type's name, nothing more.

However dynamic is determined at runtime, the compiler has no idea of the actual type, and all method/field/property accesses with that variable will be worked out at runtime.


This is a nice youtube video which talks about var VS Dynamic with practical demonstration.

Below is a more detailed explanation with snapshot.

Var is early binded (statically checked) while dynamic is late binded (dynamically evaluated).

Var keyword looks at your right hand side data and then during compile time it decides the left hand data type.In other words var keyword just saves you typing lot of things. Have a look at the below image where when we have given string data and x variable shows string data type in my tool tip.

enter image description here

On the other hand dynamic keyword is for completely different purpose. Dynamic objects are evaluated during runtime. For instance in the below code the "Length" property exists or not is evaluated during runtime.I have purposely typed a small "l" , so this program compiled fine but when it actually executed it throwed up a error when the "length" property was called ( SMALL "l").

enter image description here


dynamic variable and var variable both can store any type of value but its required to initialize 'var' at the time of declaration.

Compiler doesn't have any information about the 'dynamic' type of variable. var is compiler safe i.e compiler has all information about the stored value, so that it doesn't cause any issue at run-time.

Dynamic type can be passed as function argument and function also can return it. Var type can not be passed as function argument and function can not return object type. This type of variable can work in the scope where it defined.

In case of dynamic Casting is not require but you need to know the property and methods related to stored type , while for var No need to cast because compiler has all information to perform operation.

dynamic: Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code.

var: Useful when getting result out of the linq queries. In 3.5 framework it introduce to support linq feature.

Reference : Counsellingbyabhi


  1. Var and dynamic define type.
  2. var at the compile time while dynamic are at run time.
  3. in the var declaration and initialization both are mandatory like constant variable while
  4. in dynamic initialization can be at run time like readonly variables.
  5. in var type whatever type are decided at the time initialization can not change next but
  6. dynamic can adopt any type even user define datatype also.

Do not confuse dynamic and var. Declaring a local variable using var is just a syntactical shortcut that has the compiler infer the specific data type from an expression. The var keyword can be used only for declaring local variables inside a method while the dynamic keyword can be used for local variables, fields, and arguments. You cannot cast an expression to var, but you can cast an expression to dynamic. You must explicitly initialize a variable declared using var while you do not have to initialize a variable declared with dynamic.


  1. The Var(Implicit typed local variable) keyword is used to define local variables.In case of Var , the underlying data type is determined at compile time itself based on the initial assignment.Once the initial assignment has been made with Var type , then it will become strongly typed.If you try to store any incompatible value with the Var type it will result in compile time error.

Example:

Var strNameList=new List<string>(); By using this statement we can store list of names in the string format. 
strNameList.add("Senthil");
strNameList.add("Vignesh");

strNameList.add(45); // This statement will cause the compile time error.

But in Dynamic type, the underlying type is determined only at run time.Dynamic data type is not checked at compile time and also it is not strongly typed.We can assign any initial value for dynamic type and then it can be reassigned to any new value during its life time.

Example:

dynamic test="Senthil";
Console.Writeline(test.GetType())  // System.String

test=1222;
Console.Writeline(test.GetType())  // System.Int32

test=new List<string>();
Console.Writeline(test.GetType())  //System.Collections.Generic.List'1[System.String]

It doesn't provide IntelliSense support also.It doesn't give better support when we give work with linq also.Because it doesn't support lambda expressions ,extension methods and anonymous methods.


Here are the differences

  • var is statically typed (compile time), dynamic is dynamically typed (run time)

  • A variable declared as var can only be used locally , dynamic variables can be passed in as params to function (function signature can define a param as dynamic but not var).

  • with dynamic the resolution of the properties happens at runtime and thats not the case with var which means at compile time any variable declared as dynamic can call a method which may or maynot exist and so the compiler would not throw an error.

  • Type casting with var not possible but with dynamic its possible (you can cast an object as dynamic but not as var).

Arun Vijayraghavan

참고URL : https://stackoverflow.com/questions/961581/whats-the-difference-between-dynamic-c-4-and-var

반응형