Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0157 dynamic type

var type relies on the C# compiler to figure out the type, while dynamic type depends on the runtime to infer the type. Compare the following code. using System; class Test { static void Main() { var i = 5; i = "rntsoft.com"; } } Compile time error: C:\g>csc Program.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(8,13): error CS0029: Cannot implicitly convert type 'string' to 'int' using System; class Test { static void Main() { dynamic i = 5; Console.WriteLine(i.GetType()); i = "rntsoft.com"; Console.WriteLine(i); Console.WriteLine(i.GetType()); } } The output: System.Int32 rntsoft.com System.String