Decarevariables.md - brainchildservices/curriculum GitHub Wiki

Slide 1

Declaring Variables

To create a variable, you must specify the type and assign it a value:

  type variableName = value;

Where type is a C# type (such as int or string), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example:-

Create a variable called name of type string and assign it the value "John":

  string name = "John";
  Console.WriteLine(name); //Output:- John

Slide 2

To create a variable that should store a number, look at the following example:

Example:-

Create a variable called myNum of type int and assign it the value 15:

  int myNum = 15;
  Console.WriteLine(myNum);  //Output:- 15

You can also declare a variable without assigning the value, and assign the value later:

Example:-

  int myNum;
  myNum = 15;
  Console.WriteLine(myNum);

Slide 3

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example:-

Change the value of myNum to 20:

  int myNum = 15;
  myNum = 20; // myNum is now 20
  Console.WriteLine(myNum);

Slide 4

Constants

However, you can add the const keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "constant", which means unchangeable and read-only):

Example

  const int myNum = 15;
  myNum = 20; // error

The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An example that is often referred to as a constant, is PI (3.14159...).

  Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.

Slide 5

Other Types

A demonstration of how to declare variables of other types:

Example:-

 int myNum = 5;
 double myDoubleNum = 5.99D;
 char myLetter = 'D';
 bool myBool = true;
 string myText = "Hello";

 You will learn more about data types in the next chapter.