Lesson 3: Data Types And Variables

1. Data Types

The varibles in C#, are categorized into the following types:

  • Value types
  • Reference types
  • Pointer types

Value Type

Value type variables can be assigned a value directly. They are derived from the classSystem.ValueType.

The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an inttype, the system allocates memory to store the value.

The following table lists the available value types in C# 2010:

TypeRepresentsRangeDefault Value
bool Boolean value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode character U +0000 to U +ffff '\0'
decimal 128-bit precise decimal values with 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D
float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
long 64-bit signed integer type -923,372,036,854,775,808 to 9,223,372,036,854,775,807 0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 32-bit unsigned integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
ushort 16-bit unsigned integer type 0 to 65,535 0

To get the exact size of a type or a variable on a particular platform, you can use the sizeofmethod. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

using System;
namespace DataTypeApplication
   class Program 
      static void Main(string[] args)
         Console.WriteLine("Size of int: {0}", sizeof(int));

When the above code is compiled and executed, it produces the following result:

Size of int: 4

Reference Type

The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.

In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example ofbuilt-in reference types are: object, dynamic, and string.

Object Type

The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.

object obj;
obj = 100; // this is boxing

Dynamic Type

You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.

Syntax for declaring a dynamic type is:

dynamic <variable_name> = value;

For example,

dynamic d = 20;

Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.

String Type

The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted.

For example,

String str = "Tutorials Point";

A @quoted string literal looks as follows:

@"Tutorials Point";

The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.

Pointer Type

Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++.

Syntax for declaring a pointer type is:

type* identifier;

For example,

char* cptr;
int* iptr;

We will discuss pointer types in the chapter 'Unsafe Codes'.

2. Type Conversion


Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms:

  • Implicit type conversion - These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.

  • Explicit type conversion - These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.

The following example shows an explicit type conversion:

using System;
namespace TypeConversionApplication 
   class ExplicitConversion 
      static void Main(string[] args) 
         double d = 5673.74; 
         int i;
         // cast double to int.
         i = (int)d;

When the above code is compiled and executed, it produces the following result:


C# Type Conversion Methods

C# provides the following built-in type conversion methods:

Sr.NoMethods & Description
1 ToBoolean

Converts a type to a Boolean value, where possible.

2 ToByte

Converts a type to a byte.

3 ToChar

Converts a type to a single Unicode character, where possible.

4 ToDateTime

Converts a type (integer or string type) to date-time structures.

5 ToDecimal

Converts a floating point or integer type to a decimal type.

6 ToDouble

Converts a type to a double type.

7 ToInt16

Converts a type to a 16-bit integer.

8 ToInt32

Converts a type to a 32-bit integer.

9 ToInt64

Converts a type to a 64-bit integer.

10 ToSbyte

Converts a type to a signed byte type.

11 ToSingle

Converts a type to a small floating point number.

12 ToString

Converts a type to a string.

13 ToType

Converts a type to a specified type.

14 ToUInt16

Converts a type to an unsigned int type.

15 ToUInt32

Converts a type to an unsigned long type.

16 ToUInt64

Converts a type to an unsigned big integer.

The following example converts various value types to string type:

using System;
namespace TypeConversionApplication 
   class StringConversion
      static void Main(string[] args)
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;


When the above code is compiled and executed, it produces the following result:




A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

The basic value types provided in C# can be categorized as:

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

C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.

Defining Variables

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, 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;

You can initialize a variable at the time of definition as:

int i = 100;

Initializing Variables

Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is:

variable_name = value;

Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as:

<data_type> <variable_name> = value;

Some examples are:

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'. */

It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.

The following example uses various types of variables:

using System;
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);

When the above code is compiled and executed, it produces the following result:

a = 10, b = 20, c = 30

Accepting Values from User

The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable.

For example,

int num;
num = Convert.ToInt32(Console.ReadLine());

The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.

Lvalue and Rvalue Expressions in C#:

There are two kinds of expressions in C#:

  • lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

  • rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and hence they may appear on the left-hand side of an assignment. Numeric literals are rvalues and hence they may not be assigned and can not appear on the left-hand side. Following is a valid C# statement:

int g = 20;

But following is not a valid statement and would generate compile-time error:

10 = 20;

Source: tutorialspoint