Variables & Data Types
Variables - Introduction
C# variables are fundamental building blocks in any C# program and are used to store data. You can assign, access, and manipulate the data with the help of variables.
What Are Variables in C#?
C# variables are the containers to store data and help you to access and manipulate the data during the program execution. A variable must be declared by using a specific data type which can store that type of value.
Why Are Variables Important in C#?
- Data Storage: Variables allow you to store data like numbers, text, and more.
- Data Manipulation: You can manipulate the data within variables to perform calculations, transformations, or display results.
- Program Flow Control: Variables help manage and control how data flows through your program.
Example
In a student management system, we may need to store a student's name, age and percentage.
string studentName = "Rahul";
int age = 22;
double percentage = 82.50;
Here, each variable stores different information about the student.
Declaring Variables in C#
Syntax
Here's the basic syntax to declare a variable: In C#, you declare a variable by specifying its data type and a variable name.
<data_type> <variable_name>;
Example
Here's the basic syntax to declare a variable: In C#, you declare a variable by specifying its data type and a variable name.
int age;
string name;
Line-by-Line Explanation
-
intdefines an integer variable. -
ageis the variable name. -
stringdefines a text variable. -
nameis the variable name.
Types of Variables in C#
C# supports several types of variables, categorized as follows:
-
Primitive Variables
The primitive variables are basic data types like int, float, char, and bool.
Example
Static Code Layout Referenceint number = 10; double pi = 3.14; -
Reference Variables
The reference variables hold references to objects in memory, like arrays and classes.
Example
Static Code Layout Referencestring name = "Alice"; int[] numbers = new int[] { 1, 2, 3 }; -
Constants
The constants are variables whose value cannot be changed once assigned.
Example
Static Code Layout Referenceconst double PI = 3.14159; -
Nullable Variables
The nullable variables can hold a null value.
Example
Static Code Layout Referenceint? age = null;
Best Practices for Using Variables in C#
Use Descriptive Names:
While declaring variables, always choose meaningful variable names
that describe the purpose of the variables to be used.
For example, use studentAge to store the age of a
student instead of x.
Follow Naming Conventions: You should follow the naming conventions when declaring the variables. C# recommends using camelCase for local variables and PascalCase for class-level variables.
For example:
int studentAge; // CamelCase for local variable
public string StudentName; // PascalCase for class-level variable
Common C# Variable Examples
Here are a few examples of variables in action to give you a better understanding:
-
Storing Student Information
In this example, we store student details such as student name, qualification, age and percentage.
C#using System; string studentName = "Sudhir"; string qualification = "Sharma"; int age = 28; float percentage = 89.56f; Console.WriteLine("Student: " + studentName); Console.WriteLine("Qualification: " + qualification); Console.WriteLine("Age: " + age); Console.WriteLine("Percentage: " + percentage);Line-by-Line Explanation
-
studentNamestores the student name. -
qualificationstores qualification information. -
agestores the student's age. -
percentagestores the student's percentage. -
Console.WriteLine()displays the information.
-
-
Performing Simple Arithmetic
This example demonstrates a basic arithmetic operation.
C#using System; int num1 = 12; int num2 = 8; int sum = num1 + num2; Console.WriteLine("Addition = : " + sum);Explanation
num1stores 12.num2stores 8.sumstores the addition result.- The output will be 20.
-
Using Boolean Variables
This example shows how a boolean variable can be used to control program flow.
C#using System; bool isMember = true; Console.WriteLine("Is Member = : " + isMember);Explanation
A
boolvariable stores eithertrueorfalse.
FAQ About C# Variables
-
What is a variable in C#?
A variable is a named memory location used to store data that a program can manipulate during execution.
-
What is the difference between int and long in C#?
The int data type is a 32-bit signed integer, whereas long type is a 64-bit signed integer. You should use long for larger numbers that exceed the range of int.
-
Can I change the value of a constant in C#?
No, C# constants cannot be changed once assigned a value.
-
What is a nullable variable in C#?
A nullable variable can hold a null value in addition to its type value. The nullable type is useful when a value is optional.
Data Types
Introduction to C# Data Types
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;
string studentName = "Ajay Jadhav";
int age = 22;
double Percentage = 78.59;
char grade = 'A';
bool isEnrolled = true;
Console.WriteLine("Student Name: " + studentName);
Console.WriteLine("Age: " + age);
Console.WriteLine("Percentage: " + Percentage + "%");
Console.WriteLine("Grade: " + grade);
Console.WriteLine("Enrolled: " + isEnrolled);
Line-by-Line Explanation
-
stringstores text. -
intstores whole numbers. -
doublestores decimal numbers. -
charstores one character. -
boolstores true or false.
Types of Data in C#
The variables in C# are categorized into the following types:
- Value types
- Reference types
- Pointer types
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 store numbers, alphabets, and floating point numbers, respectively.
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
Integral data types are used for storing whole numbers.
| C# Keyword | .NET Framework Type | Size | Range / Description |
|---|---|---|---|
| byte | System.Byte | 1 byte | 0 to 255 (Unsigned) |
| sbyte | System.SByte | 1 byte | -128 to 127 (Signed) |
| short | System.Int16 | 2 bytes | -32,768 to 32,767 |
| ushort | System.UInt16 | 2 bytes | 0 to 65,535 |
| int | System.Int32 | 4 bytes | -2.1B to 2.1B |
| uint | System.UInt32 | 4 bytes | 0 to 4.2B |
| long | System.Int64 | 8 bytes | Large numbers requiring 64 bits |
| ulong | System.UInt64 | 8 bytes | Large positive numbers requiring 64 bits |
Example
using System;
int EmployeeId = 1024;
long Salary = 5000000L;
byte ExperienceYears = 10;
Console.WriteLine("Employee Id: " + EmployeeId);
Console.WriteLine("Total Salary: " + Salary);
Console.WriteLine("Total Years Of Experience: " + ExperienceYears);
Explanation
-
EmployeeIdstores an integer employee ID. -
Salarystores a larger whole number using long. -
ExperienceYearsstores a small positive number.
Character and Boolean Data Types
| C# Keyword | .NET Framework Type | Size | Default Value | Syntax |
|---|---|---|---|---|
| char | System.Char | 2 bytes | \0 | Single quotes, e.g. 'A' |
| bool | System.Boolean | Boolean value | false | true or false |
char letter = 'g';
bool isLetter = char.IsLetter(letter); // true
bool isDigit = char.IsDigit('7'); // true
bool isSpace = char.IsWhiteSpace('\n'); // true
char upper = char.ToUpper(letter); // 'G'
Enumerations (enum)
An enum is a special data type used for defining named constant values.
using System;
JobLevel currentLevel = JobLevel.Mid;
Console.WriteLine("Current Job Level: " + currentLevel);
enum JobLevel
{
Intern,
Junior,
Mid,
Senior,
Manager
}
Line-by-Line Explanation
-
enum JobLevelcreates an enumeration. - It contains predefined job levels.
-
currentLevelstores the selected job level. -
JobLevel.Midselects the Mid level.
Structs
A struct is a value type used to encapsulate related data.
using System;
Employee emp = new Employee();
emp.Id = 101;
emp.Name = "Amit";
emp.Salary = 60000.50;
Console.WriteLine("Employee Id: " + emp.Id);
Console.WriteLine("Employee Name: " + emp.Name);
Console.WriteLine("Employee Salary: $" + emp.Salary);
struct Employee
{
public int Id;
public string Name;
public double Salary;
}
Reference Types in C#
In C#, a reference type does not hold its data directly. Instead, it holds a reference that tells the computer where the object is stored in memory.
In other words, they refer to a memory location. Using multiple variables, the reference types can refer to the same object. If the object is changed through one variable, the change can be seen through another variable referring to the same object.
The "Real World" Analogy
Think of a Value Type like a dollar bill in your wallet. You hold the actual value right there. If you give a copy to a friend, they have their own dollar bill.
Think of a Reference Type like a home address written on a piece of paper. The paper doesn't contain a house; it just tells you where the house is. If you copy the address onto a second piece of paper, both papers can point to the same house.
Common Built-in Reference Types
- class: Used to create custom objects like Person or Car.
- string: Used to hold text like "Hello World".
- Array: Collections of data like int[] or string[].
- interface, delegate, and record: Advanced building blocks.
How It Works in Code (Example)
Let's see what happens when we copy a reference type. Imagine we have a simple class called Car:
class Car
{
public string Name;
}
Now, let's look at what happens in the main program.
using System;
// 1. Create a new car and give it a name
Car car1 = new Car();
car1.Name = "Swift";
// 2. Copy car1 into car2
Car car2 = car1;
// 3. Change the name using car2
car2.Name = "Creta";
Console.WriteLine("Car 1 Name: " + car1.Name);
Console.WriteLine("Car 2 Name: " + car2.Name);
Line-by-Line Explanation
-
Car car1 = new Car();creates a Car object. -
car1.Name = "Swift";gives the car a name. -
Car car2 = car1;copies the reference. - Both variables refer to the same Car object.
-
car2.Name = "Creta";changes the object's name. -
Therefore,
car1.Namealso becomes Creta.
Value Types vs. Reference Types
| Feature | Value Types | Reference Types |
|---|---|---|
| What is stored? | The actual data directly | A reference to the object |
| Examples | int, bool, double, struct | class, string, array |
| When copied | Value is copied | Reference is copied |
| Can it be null? | Normally no, nullable value types can use null | Reference variables can be null |
FAQ on Data Types
-
What is the main difference between a Value Type
and a Reference Type?
- Value Types store their actual data directly. Examples include int, double, bool, and struct.
- Reference Types refer to an object. Examples include class, string, and arrays.
-
What does null mean?
null means "nothing" or "no reference." It means that a reference does not currently point to an object.
Practice Example
Try changing the values below and run the program. This is a simple real-world student example.
using System;
string studentName = "Rahul";
int age = 22;
double percentage = 85.50;
char grade = 'A';
bool isEnrolled = true;
Console.WriteLine("Student Name: " + studentName);
Console.WriteLine("Age: " + age);
Console.WriteLine("Percentage: " + percentage + "%");
Console.WriteLine("Grade: " + grade);
Console.WriteLine("Enrolled: " + isEnrolled);
Summary
- Variables are used to store data.
- Every variable has a data type.
- Common data types include int, double, float, char, bool and string.
- Constants cannot be changed after assignment.
- Nullable variables can represent null.
- Value types store values directly.
- Reference types refer to objects.
- enum is used for named constant values.
- struct is a value type used to group related data.