var Versus dynamic - CSharp Custom Type

CSharp examples for Custom Type:dynamic type

Introduction

var meant "Let the compiler figure out the type."

dynamic meant "Let the runtime figure out the type."

To illustrate:


dynamic x = "hello";  // Static type is dynamic, runtime type is string
var y = "hello";      // Static type is string, runtime type is string
int i = x;            // Runtime error      (cannot convert string to int)
int j = y;            // Compile-time error (cannot convert string to int)

The static type of a variable declared with var can be dynamic:

dynamic x = "hello";
var y = x;            // Static type of y is dynamic
int z = y;            // Runtime error (cannot convert string to int)

Related Tutorials