Constants & Variables in C#
A variable is a named memory location. They are programming elements that can change during program execution. Data that needs to be stored in memory & accessed at a later time are stored in variables. Instead of referring to the memory location by the actual memory address you refer to it with a variable name.
Variables are declared as follows:
int a;
float b;
char c;
They can also be initialized at the time of declaration as follows: int a = 10; float b = 52.3; char c = 'k';
Constants are very similar to variables. The main difference
is that the value contained in memory cannot be changed once the constant is
declared. When you declare a constant its value is also specified and this
value cannot be changed during program execution.
Constants are used in situations where we need to keep the
value in some memory location constant. If you use hard-coded values, and the
value is changed then it has to be changed in all the locations in the code
where it has been used. Instead if we are using constants, all we will need to
do is to change the value of the constant. This would propagate the changes to
our entire application.
Constants are declared as follows
const int a;
Simple
Types (Primitive Data types)
Simple or value type variables are those, which are assigned
space in the stack instead of the heap. All the primitive types such as int,
double etc are value type variables. The simple types basically consist of
Boolean and Numeric types, where Numeric is further divided into Integral and
Floating Point.
The first rule of value types is that they cannot be null. Anytime you declare a variable of value type, you have allocated the number of bytes associated with that type on the stack and are working directly with that allocated array of bits. In addition, when you pass a variable of value type, you are passing that variable’s value and not a reference to the underlying object.
Object Type
Object type or reference type variables are those, which are
allocated storage space in the heap. Reference type objects can be null. When a
reference type is allocated under the covers a value is allocated on the heap
and a reference to that value is returned. There are basically four reference
types: classes, interfaces, delegates and arrays.
Class Type
Custom data types are available
in .NET framework in the form of classes or class type. It is nothing but a set
of data and related behavior that is defined by the developer.
Object type and class type are both reference type variables. The only difference comes from the fact that object type consists of objects predefined and available with the .NET framework such as string whereas class type consists of custom user defined data types such as the class employee given below
class employee { int empid; string empname public employee() { empid = 1001;
empname = “Ravan"
}