Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Module 2: C# Language Basics

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.

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.

Static Code Layout Reference
<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.

Static Code Layout Reference
int age;
string name;

Types of Variables in C#

C# supports several types of variables, categorized as follows:

  1. Primitive Variables

    The primitive variables are basic data types like int, float, char, and bool.

    Example
    Static Code Layout Reference
    int number = 10;
    double pi = 3.14;

  2. Reference Variables

    The reference variables hold references to objects in memory, like arrays and classes.

    Example
    Static Code Layout Reference
    string name = "Alice";
    int[] numbers = new int[] { 1, 2, 3 };

  3. Constants

    The constants are variables whose value cannot be changed once assigned.

    Example
    Static Code Layout Reference
    const double PI = 3.14159;
  4. Nullable Variables

    The nullable variables can hold a null value.

    Example
    Static Code Layout Reference
    int? 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:
Static Code Layout Reference
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:

  1. Storing Student Information

    In this example, we store student details such as student name, qualification, age and percentage.

    Static Code Layout Reference
    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);

  2. Performing Simple Arithmetic

    This example demonstrates a basic arithmetic operation.

    Static Code Layout Reference
    int num1 = 12;
    int num2 = 8;
    int sum = num1 + num2;
    Console.WriteLine("Addition = : " + sum);

  3. Using Boolean Variables

    This example shows how a boolean variable can be used to control program flow.

    Static Code Layout Reference
    bool isMember = true;
    Console.WriteLine("Is Member = : " + isMember);

FAQ About C# Variables
  1. What is a variable in C#?

    A variable is a named memory location used to store data that a program can manipulate during execution.

  2. 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.

  3. Can I change the value of a constant in C#?

    No, C# constants cannot be changed once assigned a value. The values can be assigned during the compilation time..

  4. What is a nullable variable in C#?

    A nullable variable can hold a null value in addition to its type value. The nullable type makes the variable useful for scenarios where 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
Static Code Layout Reference
<data_type> <variable_name> = <value>;
Example of C# Data Types
Static Code Layout Reference
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);
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 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:

Static Code Layout Reference
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

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 (Most common integer)
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
Static Code Layout Reference
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);
Character and Boolean Data Types

C# Keyword .NET Framework Type Size Default Value Syntax
char System.Char 2 bytes (16 bits) \0 (Null) Enclosed in single quotes (e.g., 'A')
bool System.Boolean 1 byte (8 bits) false true or false keywords

Static Code Layout Reference
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.

Static Code Layout Reference
enum JobLevel { Intern, Junior, Mid, Senior, Manager }
JobLevel currentLevel = JobLevel.Mid;
Console.WriteLine("Current Job Level: " + currentLevel);
Character and Boolean Data Types

C# Keyword .NET Framework Type Size Default Value Syntax
char System.Char 2 bytes (16 bits) \0 (Null) Enclosed in single quotes (e.g., 'A')
bool System.Boolean 1 byte (8 bits) false true or false keywords

Static Code Layout Reference
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'
Structs

A struct is a value type used to encapsulate related data.

Static Code Layout Reference
struct Employee
{
public int Id;
public string Name;
public double Salary;
}

Employee emp;
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);
Reference Types in C#

In C#, a reference type does not hold its data directly. Instead, it holds a pointer (an address) that tells the computer where the data is hidden in memory.

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.

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 and give it to a friend, both papers point to the exact same house. If your friend paints the front door red, you will see a red door too, because you are looking at the same house

Common Built-in Reference Types

Here are the most common reference types you will use in C#

  • class: Used to create custom objects (like a Person or Car object)
  • 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:

Static Code Layout Reference
class Car
{
   public string Name;
}

Now, let's look at what happens in the main program

Static Code Layout Reference
// 1. Create a new car and give it a name
Car car1 = new Car();
car1.Name = "Swift";
// 2. Copy car1 into car2
Dog car2 = car1;
// 3. Change the name using car2
car2.Name = "Creta";
Value Types vs. Reference Types

Feature Value Types (e.g., int, bool) Reference Types (e.g., class, string)
What is stored? The actual data directly A memory address pointing to the data.
Memory Location Stored on the Stack (fast, temporary memory). Stored on the Heap (flexible, managed memory).
When you copy (=) Creates a brand new copy of the data. Copies only the address; both point to the same object.
Can it be null? No, they always have a default value (like 0). Yes, null means the variable points to no address.

FAQ on Data Types

  1. What is the main difference between a Value Type and a Reference Type?

    • Value Types store their actual data directly inside the variable. They live in a fast memory area called the Stack. Examples include int, double, bool, and struct.

    • Reference Types do not store the data itself. Instead, they store a memory address (a pointer) that tells the computer where the data is kept in a larger memory area called the Heap. Examples include class, string, and arrays.

  2. What does null mean?

    null means "nothing" or "no reference." Only reference types can be null. It means the variable exists, but it is not pointing to any address or object in memory yet.