In this source code example, we will demonstrate the usage var keyword in C# with an example.
Variables at method scope can be implicitly typed using the var keyword. The variables are always strongly typed, but with var the type is inferred by C# compiler from the right side of the assignment.
On the left side of the assignment, we use the var keyword. The name variable is of string type and the age of int. The types are inferred from the right side of the assignment:
C# var Keyword Example
In the program, we have two implicitly typed variables.using System;
public class HelloWorld
{
public static void Main (string[] args)
{
var name = "John";
var age = 30;
Console.WriteLine($"{name} is {age} years old");
name = "Tom";
age = 32;
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());
}
}
Output:
John is 30 years old
Tom is 32 years old
System.String
System.Int32
var name = "John";
var age = 30;
We determine the types of the variables with GetType.
Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());
Comments
Post a Comment