Lesson 2: Variables

Alright, now that we have the basics down, we are moving on to variables. In C# there are multiple types of variables.  Here are the general types of variables listed below in the chart.

Type Example
Integral (numbers) types sbyte, byte, short, ushort, int, uint, long, ulong and char
Floating (representing numbers approximately) point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types

 

In general C# variables follow this format:

<data_type> <variable_list>;

 In C# you do not need to initialize your variables when you declare them. For example:

 
//these are valid variable declaration.
int i, j, k;
char c, ch;
float f, salary;
double d;

//however if you want to initialize them you can. Like this:
int i = 100;

//here are more initialization:
int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */

Now that we know about the variables, here is the example code that explores variables.

namespace Variables
{
    class Program
    {
        static void Main(string[] args)
        {
            short a;
            int b ;
            double c;

            /* actual initialization */
            a = 10;
            b = 20;
            c = a + b;
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.ReadLine();
        }
    }
}

This code should produce the following:

a = 10, b = 20, c = 30

If you want to read from the console, you can use the following:

 
Console.ReadLine();

//and to use it to get an integer:
int num;
num = Convert.ToInt32(Console.ReadLine());

Leave a Reply

Your email address will not be published. Required fields are marked *