Variables and Types
Variables and Types
C# is a statically-typed language. Therefore, we must define the types of variables before using them.
To define a variable in C#, we use the following syntax, which is similar to C / Java:
Notice that defining a floating-point number requires an explicit f
letter after the number.
var keyword
C# supports var
keyword - which means that you don't always have to explicitly specify a type - you can let the compiler try and understand the type of variable automatically. However, once the type of variable has been determined, it cannot be assigned a different type:
Exercise
Define three variables:
A string
named productName equal to TV
An int
named productYear equal to 2012
A float
named productPrice equal to 279.99f
Type Conversion
C# types are not the same! In some cases, you have to convert a value's type. There are two methods:
By explicitly casting it:
int x = (int) 1.0;
By using methods:
int y = Convert.ToInt32(1.0);
Read more on official documentation
Exercise
Convert myDBL to int and print it.
Last updated