[edit] C# Variables
A variable can be created by giving it a type and name(identifier). Variables can be initialized with a default value or can be initialized without being assigned a value.
int var1;
- int is the type
- var1 is the identifier or the name of the value
char value1;
- char is the type
- value1 is the identifier or the name of the value
Lets take a look at some code:
using System; class Program { static void Main(string[] args) { int a; //Declare a variable a = 3; //Initialize 'a' with a value of 3 Console.WriteLine(a); //Print the variable Console.Read(); } }
Output
- Line 7: declares a variable a of type int.
- Line 9: initializes the variable a with the value 3.
- Line 10: prints the value in variable a.
Run the code above
[edit] Declare a variable and initialize it
int var1 = 91;
- var1s type is int with a value of 91
char value1 = 'c';
- value1s type is char with a value of c.
Example code
using System;
class Program
{
static void Main(string[] args)
{
int a = 23;
char b = 's';
Console.WriteLine(a);
Console.WriteLine(b);
Console.Read();
}
}
Output
Run this code.
[edit] Declare multiple variables
You are able to declare multiple variable on one line. Here is how to do it:
int var1 = 3, var2 = 78, var3, var4 = 0;
- Notice: var3 is not initialized. Before you can use it you must initialize it first.
char value1 = 'z', value2 = 'a', value3, value = 'e';
- Notice: value3 is not initialized. Before you can use it you must initialize it first.
int var1 = 3, char var2 = 'w';
- Notice: you can only use the same types. Do you see int with char? This is an error.
|