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:

int myInt = 1;
float myFloat = 1f;
bool myBoolean = true;
string myName = "John";
char myChar = 'a';
double myDouble = 1.75;

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:

var x = 1;
var y = 2;
var sum = x + y;    // sum will also be defined as an integer

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

using System;

public class Program
{
   public static void Main()
   {
      // write your code here
      
      // Do not modify code below!
      Console.WriteLine("productName: " + productName);
      Console.WriteLine("productYear: " + productYear);
      Console.WriteLine("productPrice: " + productPrice);

   }
}

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.

using System;

public class Program
{
    public static void Main()
    {
        double myDBL = 99.0;
    
    }
}

Last updated