Explicit declarations
Explicit declaration is where the type of the variables is specified during declaration.
int age = 23;
string name = "Lorem Ipsum";
double money = 123.45;
Console.WriteLine($"Type of age: {age.GetType()}");
Console.WriteLine($"Type of name: {name.GetType()}");
Console.WriteLine($"Type of money: {money.GetType()}");
Output:
Type of age: System.Int32
Type of name: System.String
Type of money: System.Double
Live-code example
Implicit declarations
C# compiler uses type inferencing to deduce the actual type of the variable declared with the keyword var
. Note that (Docs, 2015)
var
keyword can only be used for variables declared at method scope- an implicitly declared variable is strongly typed (just as if you had declared the type yourself), which is different from the
dynamic
type.
var age = 23;
var name = "Lorem Ipsum";
var money = 123.45;
Console.WriteLine($"Type of age: {age.GetType()}");
Console.WriteLine($"Type of name: {name.GetType()}");
Console.WriteLine($"Type of money: {money.GetType()}");
Output:
Type of age: System.Int32
Type of name: System.String
Type of money: System.Double
This is not allowed since age
is statically-typed (as int
)
// ERROR: Cannot implicitly convert type "string" to "int"
age = "123";
Implicit declaration is extremely useful for creating anonymous classes, which are used extensively in LINQ operation.
var anony = new {
Name = "Lorem Ipsum",
Age = 23,
Money = 123.45
};
Console.WriteLine($"Type: {anony.GetType()}");
Console.WriteLine($"Name: {anony.Name} Age: {anony.Age} Money: {anony.Money}");
Output:
Type: <> f__AnonymousType0`3[System.String, System.Int32, System.Double] <-- this will be different
Name: Lorem Ipsum Age: 23 Money: 123.45
References
- Docs, M. (Ed.). (2015, July 20). var (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var