C# - Variables: Type Example
C# - Variables: Type Example
A variable is nothing but a name g iven to a storag e area that our prog rams can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory; the rang e of values that can be stored within that memory; and the set of operations that can be applied to the variable. We have already discussed various data types. T he basic value types provided in C# can be categ orized as:
T ype Integ ral types Floating point types Decimal types Boolean types Nullable types
Example sbyte, byte, short, ushort, int, uint, long , ulong and char float and double decimal true or false values, as assig ned Nullable data types
C# also allows defining other value types of variable like enum and reference types of variables like c lass , which we will cover in subsequent chapters. For this chapter, let us study only basic variable types.
Variable Definition in C#
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid variable definitions are shown here:
int i, j, k; char c, ch; float f, salary; double d;
Variable Initialization in C#
Variables are initialized (assig ned a value) with an equal sig n followed by a constant expression. T he g eneral form of initialization is:
variable_name = value;
Variables can be initialized (assig ned an initial value) in their declaration. T he initializer consists of an equal sig n followed by a constant expression as:
<data_type> <variable_name> = value;
/* /* /* /*
initializing d and f. */ initializes z. */ declares an approximation of pi. */ the variable x has the value 'x'. */
It is a g ood prog ramming practice to initialize variables properly, otherwise sometimes prog ram would produce unexpected result. T ry the following example which makes use of various types of variables:
namespace VariableDefinition { 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(); } } }
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
T he function Convert.T oInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
But following is not a valid statement and would g enerate compile-time error:
10 = 20;