
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# - Data Types
Introduction to C# Data Types
C# data types define the type of data a variable can store, such as integers, floating-point numbers, characters, or Boolean values. The data types are essential to declare specific variables to store the related value, memory optimization, performance improvements, and code readability.
In this chapter, you will learn:
- Different C# data types.
- Declaring and assigning the variable with the use of specific data types.
- Best practices about C# data types to write efficient code.
- Common mistakes to avoid while declaring and using the data types.
What Are Data Types in C#?
C# data types specify the type of data that variables can store. In C#, all variables must be declared with the data types before their use, as it is a strongly typed language.
Syntax for Declaring a Variable with Data Type
<data_type> <variable_name> = <value>;
Example of C# Data Types
using System; class Program { static void Main() { string studentName = "Sudhir Sharma"; int studentAge = 20; double marksPercentage = 85.5; char grade = 'A'; bool isEnrolled = true; Console.WriteLine("Student Name: " + studentName); Console.WriteLine("Age: " + studentAge); Console.WriteLine("Marks Percentage: " + marksPercentage + "%"); Console.WriteLine("Grade: " + grade); Console.WriteLine("Enrolled: " + isEnrolled); } }
This example will produce the following output:
Student Name: Sudhir Sharma Age: 20 Marks Percentage: 85.5% Grade: A Enrolled: True
Types of Data in C#
The variables in C#, are categorized into the following types −
- Value types
- Reference types
- Pointer types
1. Value Types in C#
Value type variables can be assigned a value directly. They are derived from the class System.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 int type, the system allocates memory to store the value.
Value types store actual values and include:
- Integral types (int, byte, long, etc.)
- Floating-point types (float, double, decimal)
- Character type (char)
- Boolean type (bool)
- Enumerations (enum)
- Structs (struct)
Integral Data Types
Data Type | Size | Range |
---|---|---|
byte | 1 byte | 0 to 255 |
sbyte | 1 byte | -128 to 127 |
short | 2 bytes | -32,768 to 32,767 |
ushort | 2 bytes | 0 to 65,535 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
uint | 4 bytes | 0 to 4,294,967,295 |
long | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
ulong | 8 bytes | 0 to 18,446,744,073,709,551,615 |
Example
using System; class Program { static void Main() { int studentID = 1024; long salary = 5000000L; byte experienceYears = 10; Console.WriteLine("Student ID: " + studentID); Console.WriteLine("Employee Salary: " + salary); Console.WriteLine("Experience (Years): " + experienceYears); } }
This example will produce the following output:
Student ID: 1024 Employee Salary: 5000000 Experience (Years): 10
Floating-Point Data Types
Data Type | Size | Precision |
---|---|---|
float | 4 bytes | 6-7 decimal places |
double | 8 bytes | 15-16 decimal places |
decimal | 16 bytes | 28-29 decimal places |
Example
using System; class Program { static void Main() { float gpa = 3.85f; double distance = 384400.5; decimal accountBalance = 15249.75m; Console.WriteLine("Student GPA: " + gpa); Console.WriteLine("Distance to Moon (km): " + distance); Console.WriteLine("Bank Account Balance: $" + accountBalance); } }
This example will produce the following output:
Student GPA: 3.85 Distance to Moon (km): 384400.5 Bank Account Balance: $15249.75
Use float
and double
for general calculations.
Use decimal
for precise financial calculations.
Character and Boolean Data Types
Data Type | Size | Description |
---|---|---|
char | 2 bytes | Stores a single character |
bool | 1 byte | Stores true or false |
Example
using System; class Program { static void Main() { bool isGraduate = true; char section = 'B'; Console.WriteLine("Graduated: " + isGraduate); Console.WriteLine("Class Section: " + section); } }
This example will produce the following output:
Graduated: True Class Section: B
Enumerations (enum)
An enum
is a special data type used for defining named constant values.
Example
using System; class Program { enum JobLevel { Intern, Junior, Mid, Senior, Manager } static void Main() { JobLevel currentLevel = JobLevel.Mid; Console.WriteLine("Current Job Level: " + currentLevel); } }
This example will produce the following output:
Current Job Level: Mid
Structs
A struct
is a value type used to encapsulate related data.
Example
using System; struct Employee { public int ID; public string Name; public double Salary; } class Program { static void Main() { Employee emp; emp.ID = 101; emp.Name = "Zoya"; emp.Salary = 60000.50; Console.WriteLine("Employee ID: " + emp.ID); Console.WriteLine("Employee Name: " + emp.Name); Console.WriteLine("Employee Salary: $" + emp.Salary); } }
This example will produce the following output:
Employee ID: 101 Employee Name: Zoya Employee Salary: $60000.5
2. Reference Types in C#
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 of built-in reference types are: object, dynamic,, string, and array.
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
Example
using System; class Program { static void Main() { object obj = 1001; // Student ID Console.WriteLine("Student ID: " + obj); obj = "Sudhir Sharma"; // Student Name Console.WriteLine("Student Name: " + obj); } }
This example will produce the following output:
Student ID: 1001 Student Name: Sudhir Sharma
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;
Example
using System; class Program { static void Main() { dynamic value = 10; Console.WriteLine("Dynamic value: " + value); value = "Hello, World!"; Console.WriteLine("Dynamic now contains: " + value); } }
This example will produce the following output:
Dynamic value: 10 Dynamic now contains: Hello, World!
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.
Example
using System; class Program { static void Main() { string firstName = "Sudhir"; string lastName = "Sharma"; string fullName = firstName + " " + lastName; Console.WriteLine("Full Name: " + fullName); } }
This example will produce the following output:
Full Name: Sudhir Sharma
Note: Use StringBuilder for modifying strings efficiently.
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.
Array Type
Arrays store multiple values of the same type in a single variable.
Example
using System; class Program { static void Main() { string[] students = { "Zoya", "Yashna", "Olivia", "Naomi" }; Console.WriteLine("Student List:"); foreach (string student in students) { Console.WriteLine(student); } } }
This example will produce the following output:
Student List: Zoya Yashna Olivia Naomi
3. Pointer Type in C#
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;
Example
using System; unsafe class Program { static void Main() { int grade = 90; int* ptr = &grade; Console.WriteLine("Original Grade: " + grade); Console.WriteLine("Memory Address: " + (ulong)ptr); *ptr = 95; // Modifying value using pointer Console.WriteLine("Updated Grade: " + grade); } }
This example will produce the following output:
main.cs(3,1): error CS0227: Unsafe code requires the `unsafe' command line option to be specified Compilation failed: 1 error(s), 0 warnings
Type Conversion in C#
There may be situations where you need to change the type of a variable. Type conversion allows you to convert data from one type to another. In C#, there are two types of type conversions: implicit and explicit.
1. Implicit Conversion (Safe)
Implicit conversion occurs automatically when there is no risk of data loss. C# allows implicit conversion for compatible types.
Example
using System; class Program { static void Main() { int studentAge = 18; double preciseAge = studentAge; // Implicit conversion Console.WriteLine("Student Age (Integer): " + studentAge); Console.WriteLine("Converted to Double: " + preciseAge); } }
This example will produce the following output:
Student Age (Integer): 18 Converted to Double: 18
2. Explicit Conversion (Casting)
Explicit conversion is required when converting between incompatible types. This is done using casting.
Example
using System; class Program { static void Main() { double salary = 50000.75; int roundedSalary = (int)salary; // Explicit casting Console.WriteLine("Original Salary (Double): " + salary); Console.WriteLine("Rounded Salary (Integer): " + roundedSalary); } }
This example will produce the following output:
Original Salary (Double): 50000.75 Rounded Salary (Integer): 50000
Best Practices for Using Data Types in C#
- Choose the right data type: Using the correct data type helps save memory and makes your program efficient.
-
Use
var
when the type is obvious: It improves readability and makes the code cleaner. - Avoid unnecessary type conversions: Converting data types too often can slow down performance.
-
Use
const
orreadonly
for fixed values: These help prevent accidental changes to important values. -
Use
decimal
for money-related calculations: It provides more accuracy for financial transactions.
Common Mistakes to Avoid
1. Using an Incorrect Data Type
// Error: Should use `decimal` float price = 100.99f;
Fix: Use decimal
for money-related calculations.
decimal price = 100.99m;
2. Not Handling Null Values in Reference Types
// This will cause a NullReferenceException string name; Console.WriteLine(name.Length);
Fix: Always initialize strings before using them.
string name = "sudhir"; Console.WriteLine(name.Length);
3. Ignoring Type Compatibility in Assignments
// Compilation error: Cannot assign a string to an int int age = "25";
Fix: Convert the string properly before assigning it to an integer.
int age = int.Parse("25"); // or Convert.ToInt32("25")
FAQ About C# Data Types
Q1: What is the difference between float, double, and decimal?
- float is used for approximate calculations.
- double provides more precision.
- decimal is best for financial data.
Q2: Can I store an integer in a char variable?
No, but you can cast an integer to a char:
char c = (char)65; // Outputs 'A'
Q3: What is the best way to store large numbers?
Use long for large integers and double for large floating-point values.