</>
Skip to content
C# lessons (7/34)

C# — Variables

Declaration and initialization

using System;

// Explicit type
int age = 30;
string name = "Alice";
double pi = 3.14;
bool isActive = true;

// var (type inferred)
var score = 95;      // int
var price = 19.99;   // double
var greeting = "Hi"; // string

Console.WriteLine($"{name} is {age} years old");

Naming rules

  • Must start with a letter or underscore
  • Can contain letters, numbers, underscores
  • Case-sensitive (myVar ≠ MyVar)
  • Cannot be a C# keyword
  • Use PascalCase for public members, camelCase for locals
int count = 5;     // Valid
int _private = 10; // Valid
int myVar2 = 20;   // Valid
// int 2count = 30; // Invalid

Constants and readonly

using System;

// const: compile-time constant
const double Pi = 3.14159;
const int MaxSize = 100;

// readonly: runtime constant (can be set in constructor)
readonly string ConnectionString;

public class Config
{
    public Config(string conn)
    {
        ConnectionString = conn; // Set in constructor
    }

    // ConnectionString = "new"; // Error: readonly
}

Scope

using System;

class Program
{
    static int classVar = 100; // Class-level

    static void Main()
    {
        int localVar = 50; // Method-level

        if (localVar > 25)
        {
            int blockVar = 25; // Block-level
            Console.WriteLine(blockVar);
        }
        // Console.WriteLine(blockVar); // Error: out of scope

        for (int i = 0; i < 3; i++)
        {
            // i is scoped to the for block
        }
        // Console.WriteLine(i); // Error: out of scope
    }
}

Nullable types

using System;

// Value types can be nullable with ?
int? age = null;
double? price = null;
bool? isActive = null;

// Check for null
if (age.HasValue)
{
    Console.WriteLine($"Age: {age.Value}");
}

// Null-coalescing operator
int actualAge = age ?? 0;

// Null-conditional operator
string? name = GetName();
int? length = name?.Length;

Type checking

using System;

var x = 42;
Console.WriteLine(x.GetType()); // System.Int32

// is keyword
if (x is int)
{
    Console.WriteLine("x is an integer");
}

// Pattern matching
object obj = "Hello";
if (obj is string s)
{
    Console.WriteLine($"String of length {s.Length}");
}

Type conversion

using System;

// Implicit conversion (safe)
int i = 42;
long l = i;     // int → long
double d = i;   // int → double

// Explicit conversion (may lose data)
double pi = 3.14159;
int truncated = (int)pi; // 3

// Parse and TryParse
string numStr = "42";
int parsed = int.Parse(numStr);
bool success = int.TryParse("abc", out int result);

Console.WriteLine($"Parsed: {parsed}");
Console.WriteLine($"TryParse success: {success}");

// Convert class
int fromDouble = Convert.ToInt32(3.14);
string fromInt = Convert.ToString(42);

var vs explicit types

Use var whenUse explicit type when
Type is obvious from RHSType isn't obvious
Using new keywordDeclaration needs clarity
LINQ queriesPublic API parameters
Tuple deconstructionWorking with literals

Mini Practice

Write C# code that:

  1. Declares variables of each primitive type
  2. Uses const and readonly
  3. Demonstrates nullable types and null checking
  4. Shows type conversion with Parse and TryParse

Up Next

In the next lesson, you'll learn about Data Types — value and reference types in C#.

Related Topics

Frequently Asked Questions about Variables

What is Variables in C#?

Variables is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Variables?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.

Why is Variables important in C#?

Variables is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.