Home »
.Net
Implicit type variable in C# with Example
Learn: What are the implicit type variables in C#.Net? How to declare them? Tutorial of implicit type variables in C# with Example.
In the last post we have discussed about the C# predefined data types, their declarations etc. Here, we are going to discuss about the Implicit type variables in C#, how they declared and used in C# program?
What is C# implicit type variable?
In the normal variable declarations, we have to define their data types along with the variable name but using implicit we do not need to define the data type.
It is a special type of variable, which does not need to define data type. We can declare an implicit type variable by using var keyword, the type of variable is identified at the time of compilation depending upon the value assigned to it.
Consider the declarations:
var x = 100; // x is of type int.
var s = "Hello"; // s is of type string
var f = 3.14f; // f is of type float
var y; // invalid
In this process of declaring a variable without assigning a value is not possible.
Consider the given example:
using System;
class TypesDemo
{
static void Main()
{
var x=10;
Console.WriteLine(x.GetType());
var f =3.14f;;
Console.WriteLine(f.GetType());
var d=3.14m;
Console.WriteLine(d.GetType());
}
}
Output
System.Int32
System.Single
System.Decimal
Press any key to continue . . .
In above program x, f, d there are three different variables. They declared using var keyword but depending on assigning values they understand their types. For more clarity we are printing their types by using GetType() method.