Type inference makes use of the var keyword. The syntax for declaring the variable changes a bit. The compiler of "clear" what the rate is variable so the variable is initialized. For example,
int someNumber = 0;
becomes
var someNumber = 0;
Although someNumber never been declared as an int, the compiler of the figures in this and someNumber is an int by the time and in scope. Once compiled, the two statements above are equal.
Here is a short program
using System;
namespace Wrox.ProCSharp.Basics
{
class Program
{
static void Main(string[] args)
{
var name = “Bugs Bunny”;
var age = 25;
var isRabbit = true;
Type nameType = name.GetType();
Type ageType = age.GetType();
Type isRabbitType = isRabbit.GetType();
Console.WriteLine(“name is type “ + nameType.ToString());
Console.WriteLine(“age is type “ + ageType.ToString());
Console.WriteLine(“isRabbit is type “ + isRabbitType.ToString());
}
}
}
The output from this program is:
name is type System.String
age is type System.Int32
isRabbit is type System.Bool
There are some rules to follow. The variable must be initialized. Otherwise, the compiler That has nothing to deduce the type. The initializer can not be null, and the initializer must be a expression. You can configure the initialization of an object unless you create a new object initialization.
0 comments:
Post a Comment