C# Data Types And Variables with examples

In this tutorial we will learn C# Data Types And Variables. We can also Learn how to Define, Initialize and Declare a Variable Along with Various Data Types in C#.

C# DATA TYPES AND VARIABLES

We discussed about C# Program Structure and Basic Program in our previous tutorial.

For easy understanding, in this C# tutorial will learn all about C# Data Types And Variables with simple examples.

C# is a strongly typed language, which means that every variable and expression has a specific data type that determines the range of values it can hold and the operations that can be performed on it.

Some common data types in C# include:

1.int – In C#, the integer data type is represented by the keyword int. It is a 32-bit signed integer and can hold values ranging from -2,147,483,648 to 2,147,483,647. Here’s an example of declaring and using an int variable in C#:

int myNumber = 42;
Console.WriteLine("My favorite number is " + myNumber);

In this example, we declare an int variable called myNumber and assign it the value of 42. We then use the Console.WriteLine() method to print a message to the console that includes the value of myNumber.

2. double – In C#, the ‘double‘ data type is used to represent double-precision floating-point numbers. It occupies 8 bytes of memory and can store a wide range of values with high precision.

Here’s an example of using double in C#:

double x = 3.14159;

double x = 3.14159; // declare a double variable and initialize it with a value

double y = x * 2; // perform a mathematical operation on the double variable

Console.WriteLine("x = {0}", x); // output the value of x to the console

Console.WriteLine("y = {0}", y); // output the value of y to the console

In this example, we declare a double variable x and initialize it with the value of 3.14159. We then perform a mathematical operation on x by multiplying it by 2 and store the result in another double variable y. Finally, we output the values of x and y to the console using the Console.WriteLine method.

The output of this program would be:

x = 3.14159
y = 6.28318

As you can see, the double data type is useful when you need to store floating-point values with a high degree of precision.

3. bool – used for boolean values (true or false)

bool isTrue = true;
bool isFalse = false;

if (isTrue)
{
    Console.WriteLine("The value of isTrue is true.");
}
else
{
    Console.WriteLine("The value of isTrue is false.");
}

if (isFalse)
{
    Console.WriteLine("The value of isFalse is true.");
}
else
{
    Console.WriteLine("The value of isFalse is false.");
}

In this example, we declare two boolean variables named isTrue and isFalse. The first variable is initialized with the value true, and the second variable is initialized with the value false.

We then use an if statement to check the value of each variable. The first if statement checks whether isTrue is true, and it prints a message indicating that the value of isTrue is true. The second if statement checks whether isFalse is true, and it prints a message indicating that the value of isFalse is false.

When we run this code, the output will be:

The value of isTrue is true.char myChar = 'A';
Console.WriteLine(myChar); // Output: A

The value of isFalse is false.

4.char –In C#, the ‘char‘ data type represents a single Unicode character. It is a 16-bit value that can hold any character in the Unicode character set.

Here’s an example of how to use the char data type in C#:

char myChar = 'A';
Console.WriteLine(myChar); // Output: A

In this example, we declare a variable myChar of type char and initialize it with the character ‘A’. We then use the Console.WriteLine() method to print the value of myChar to the console.

The char data type can also be used to represent escape sequences, which are special characters that have a specific meaning in C#. Here’s an example:

char myChar = '\n';
Console.WriteLine("Hello{0}World!", myChar); // Output: 
                                             // Hello
                                             // World!

In this example, we assign the escape sequence ‘\n’ to the myChar variable, which represents a newline character. We then use the Console.WriteLine() method to print the string “Hello” followed by the value of myChar, which causes the console to print a newline before printing the string “World!”.

5. string – In C#, a ‘string‘ is a sequence of Unicode characters. The string data type is used to represent text values, such as names, addresses, and messages. Here’s an example of how to declare and use a string variable in C#:

string message = "Hello, World!";
Console.WriteLine(message);

In this example, we declare a string variable called “message” and assign it the value “Hello, World!”. We then use the Console.WriteLine() method to output the value of the string to the console.

Strings can also be concatenated using the “+” operator:

string name = "John";
string message = "Hello, " + name + "!";
Console.WriteLine(message);

In this example, we concatenate the string “Hello, ” with the variable “name” and the string “!” to create the message “Hello, John!”. We then use the Console.WriteLine() method to output the value of the message to the console.

6. decimal

In C#, the ‘decimal‘ data type is used to represent numbers with high precision, such as financial or monetary values, where accuracy is crucial.

Here’s an example of using decimal in C#:

decimal price = 12.99m;
decimal taxRate = 0.07m;
decimal totalPrice = price + (price * taxRate);

Console.WriteLine("Price: " + price);
Console.WriteLine("Tax Rate: " + taxRate);
Console.WriteLine("Total Price: " + totalPrice);

In the above example, we declare three variables of type decimal. We assign 12.99m to price and 0.07m to taxRate. We then calculate the totalPrice by adding the price and the tax amount (calculated as price * taxRate). Finally, we output the values of all three variables using Console.WriteLine().

Note that we append the m character to the end of the decimal values to indicate to the C# compiler that these are decimal literals, and not double or float literals.

7. float – In C#, the data type “float” is used to represent single-precision floating-point numbers. It occupies 4 bytes of memory and has a range of approximately ±1.5 x 10^-45 to ±3.4 x 10^38.

float myFloat = 3.14f;
Console.WriteLine(myFloat);

In this example, we declare a variable called “myFloat” of type “float” and assign it the value of 3.14. Note that we need to include the “f” suffix at the end of the value to indicate that it is a float literal.

We then use the “Console.WriteLine()” method to print out the value of “myFloat” to the console. The output would be:

3.14

Note that the precision of a “float” value is limited, which can result in rounding errors when performing calculations with very small or very large numbers. If you require higher precision, you may want to consider using the “double” data type instead.

Data TypeData SizeDescription
char2 bytesStores single character quoted in single quote.
bool1 bitStores True and False value
int4 bytesStores whole number from -2,147,483,648 to 2,147,483,647
string2 bytes per characterStores Sequence of characters quoted in double quote.
float
4 bytes
Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
Double8 bytesStores fractional numbers. Sufficient for storing 15 decimal digits
long8 bytesStores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
uint4 bytesStores unsigned integer value from
0 to 4,294,967,295
short2 bytesStores signed integer value -32,768 to 32,767
ulong8 bytesStores unsigned integer number from
0 to 18,446,744,073,709,551,615

Classification Of Data Types

The preceding section classifies data types based on the type of value they can hold and the amount of memory they consume. Additionally, data types can be broadly categorised into below two groups depending on how their values are stored in memory.

  • Reference Type
  • Value Type

1) Reference Type

Reference types do not store values directly. Instead, they store the address where the value may be located. In simpler terms, a variable of a reference type simply holds a reference to a specific memory location that could contain the necessary data.

Reference types encompass data such as strings, arrays, and classes, among others. When changes are made to the data, other variables referencing that data will automatically reflect the updated value. If a reference type variable is not assigned a value, it will contain a null value by default.

There are total three different reference type:

  1. Object Type: The object type is the base class for all objects in C#. It can hold any type of value, including value types, user-defined types, and reference types. For example:
object obj = 10; //assigning an int value to an object type variable
  1. Dynamic Type: The dynamic type can hold any type of value, and the type check is done at runtime instead of compile-time. This means that the variable can be assigned values of different types during runtime. For example:
dynamic dyn = 123; //assigning an int value to a dynamic type variable
dyn = "hello world"; //assigning a string value to the same variable during runtime
  1. String Type: The string type is used to hold a series of character values and is represented by the System.String class. It is one of the most widely used data types in C#. For example:
string str = "hello world"; //assigning a string value to a string type variable

2) Value Type

Value type data types are variables that store a data value within their own designated memory space. Therefore, these data types hold their values directly.

int i = 20;

Here the integer variable “i” is directly holding the value of 20.

C# DATA TYPES AND VARIABLES

In addition to these basic data types, C# also supports more complex data types such as arrays, classes, and structs.

C# Type Casting-Explicit and Implicit Conversion with example

In C#, type casting is the process of converting a value of one data type to another data type. Type casting is important when you want to perform operations on variables that are of different data types. There are two types of type casting in C#: implicit type casting and explicit type casting.

Implicit Type Casting:

Implicit type casting occurs when a smaller data type is converted to a larger data type. The compiler automatically performs this conversion without requiring any explicit conversion statements. For example:

int i = 10;
double d = i; //implicit conversion from int to double

In the above example, the value of i is implicitly converted to double because double can hold larger values than int.

Another example of implicit type casting is when you assign a literal value to a variable of a different data type, as shown below:

int i = 10;
long l = 1000;
float f = 1.23f;

Here, the values of 10, 1000, and 1.23f are implicitly converted to int, long, and float, respectively.

Explicit Type Casting:

Explicit type casting occurs when a larger data type is converted to a smaller data type. In this case, you must use a cast operator to perform the conversion. For example:

double d = 10.5;
int i = (int)d; //explicit conversion from double to int

In the above example, the value of d is explicitly converted to int using the cast operator (int).

Another example of explicit type casting is when you convert a variable of one data type to another data type using a cast operator. For example:

int i = 10;
long l = (long)i; //explicit conversion from int to long

Here, the value of i is explicitly converted to long using the cast operator (long).

It is important to note that explicit type casting can lead to loss of data if the value of the source data type is greater than the maximum value that can be held by the target data type. In such cases, the value is truncated or rounded off.

In summary, implicit type casting occurs when a smaller data type is converted to a larger data type, while explicit type casting occurs when a larger data type is converted to a smaller data type. Here are some examples of both types of type casting:

//Implicit type casting examples
int i = 10;
double d = i; //i is implicitly converted to double

float f = 1.23f;
double d = f; //f is implicitly converted to double

//Explicit type casting examples
double d = 10.5;
int i = (int)d; //d is explicitly converted to int

float f = 1.23f;
int i = (int)f; //f is explicitly converted to int

InvalidCastException

Sometimes it is possible that the compiler may not understand whether the operation performed to convert one type into another is valid or not. This causes the compiler to fail during the runtime. Once the type conversion fails, it will throw an Invalid exception.

InvalidCastException is thrown whenever an explicit or type conversion implementation is not supported by both the data types used for conversion.

In this tutorial, we learned about C# Variables and Data Types. We learned to define a variable and also discussed how to declare and initialize a variable. We saw the various data types that can be used to declare a variable.

Every data type in C# has its own set of ranges inside which the value is declared and has a default value stored. We also learned that, how we can convert one data type to another data type by using Implicit and Explicit conversion.

Leave a Comment

RSS
Follow by Email
YouTube
YouTube
LinkedIn
Share