Courses/C#/Variables & Data Types

    Variables & Data Types

    Lesson 2 โ€ข Beginner Track

    What You'll Learn

    • Declare variables with explicit types (int, string, double, bool, char)
    • Understand value types vs reference types in C#
    • Use var for type inference and know when it's appropriate
    • Convert between types using casting, Parse, TryParse, and Convert
    • Format output with string interpolation, currency, and decimal formatting
    • Use verbatim strings (@) and raw string literals for file paths and JSON

    ๐Ÿ’ก Real-World Analogy

    Variables are like labelled containers in a kitchen. A jar labelled "Sugar" (string) holds text, a measuring cup labelled "Cups" (int) holds whole numbers, and a scale labelled "Weight" (double) holds decimals. Each container can only hold one type of ingredient โ€” you can't pour flour into a measuring cup designed for liquids. C#'s type system works the same way: every variable has a specific type that determines what data it can store.

    ๐Ÿ“Š Common Data Types

    TypeExampleDescriptionSize
    intint age = 25;Whole numbers4 bytes
    longlong pop = 8000000000L;Large whole numbers8 bytes
    doubledouble pi = 3.14;Decimal numbers (15-16 digits)8 bytes
    decimaldecimal price = 19.99m;High precision (financial)16 bytes
    stringstring name = "Alice";Text (sequence of chars)Variable
    charchar grade = 'A';Single character2 bytes
    boolbool active = true;True or false1 byte
    varvar city = "London";Compiler infers typeDepends

    1. Declaring Variables

    Every variable in C# must have a type and a name. You can declare and assign in one step, or declare first and assign later. Use descriptive camelCase names like firstName or totalPrice.

    Basic Variables & Types

    Declare variables of different types and print them.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            // Declare and initialize variables
            string name = "Alice";
            int age = 25;
            double height = 5.7;
            bool isStudent = true;
            char grade = 'A';
    
            // Print using string interpolation
            Console.WriteLine($"Name: {name}");
            Console.WriteLine($"Age: {age}");
            Console.WriteLine($"Height: {height}ft");
            Console.WriteLine($"Student: {isStudent}");
            Console.WriteLin
    ...

    2. Type Casting & Conversion

    Sometimes you need to convert between types. Implicit casting happens automatically when it's safe (int โ†’ double). Explicit casting requires the (type) syntax and may lose data. For strings, use Parse, TryParse, or the Convert class.

    Type Casting & Conversion

    Convert between types safely using casting, Parse, and TryParse.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            // Implicit casting (safe โ€” no data loss)
            int myInt = 100;
            double myDouble = myInt;  // int โ†’ double automatically
            Console.WriteLine($"int: {myInt}, double: {myDouble}");
    
            // Explicit casting (may lose data)
            double pi = 3.14159;
            int rounded = (int)pi;  // Truncates to 3
            Console.WriteLine($"double: {pi}, int: {rounded}");
    
            // Parse strings to numbers
            string a
    ...

    3. String Interpolation & Formatting

    String interpolation ($"...") is the modern way to embed variables in strings. You can also format numbers as currency (:C), fixed decimals (:F4), or percentages (:P1). Use @"..." for file paths to avoid escaping backslashes.

    String Formatting

    Master string interpolation, number formatting, and verbatim strings.

    Try it Yourself ยป
    C#
    using System;
    
    class Program
    {
        static void Main()
        {
            string name = "John";
            int age = 30;
            decimal salary = 55000.75m;
    
            // String concatenation (old way)
            Console.WriteLine("Name: " + name + ", Age: " + age);
    
            // String interpolation (modern way)
            Console.WriteLine($"Name: {name}, Age: {age}");
    
            // Formatting numbers
            Console.WriteLine($"Salary: {salary:C}");     // Currency
            Console.WriteLine($"PI: {Math.PI:F4}"); 
    ...

    Pro Tips

    • ๐Ÿ’ก Use decimal for money, not double: double has floating-point rounding errors. decimal price = 19.99m; is precise for financial calculations.
    • ๐Ÿ’ก Prefer TryParse over Parse: int.Parse("abc") throws an exception. int.TryParse("abc", out int result) returns false safely.
    • ๐Ÿ’ก Use var wisely: var name = "Alice"; is fine when the type is obvious. Avoid var result = GetData(); when the return type isn't clear.
    • ๐Ÿ’ก Constants use const: const double PI = 3.14159; โ€” the value can never change and must be known at compile time.

    Common Mistakes

    • Forgetting the m suffix for decimal: decimal price = 19.99; won't compile โ€” you need 19.99m.
    • Integer division surprise: int result = 7 / 2; gives 3, not 3.5. Cast to double first: (double)7 / 2.
    • Using single quotes for strings: 'hello' is invalid โ€” strings use double quotes. Single quotes are for char only: 'A'.
    • Uninitialized variables: Local variables must be assigned before use. int x; Console.WriteLine(x); won't compile.
    • Overflow without checking: int.MaxValue + 1 wraps around silently. Use checked blocks to catch overflow errors.

    ๐ŸŽ‰ Lesson Complete

    • โœ… Variables store data with a specific type: int, string, double, bool, char, decimal
    • โœ… Use var for type inference when the type is obvious from the right side
    • โœ… Implicit casting is automatic and safe; explicit casting uses (type) and may lose data
    • โœ… TryParse is safer than Parse for converting strings to numbers
    • โœ… String interpolation $"..." with format specifiers (:C, :F2, :P1) for clean output
    • โœ… Use decimal for financial values, const for compile-time constants
    • โœ… Next lesson: Operators โ€” arithmetic, comparison, and logical operations

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service