×

C# Crash Course

Course Home C# Introduction and Setup C# Variables and Data Types C# Console Input and Output C# Operators and Expressions C# Conditional Statements - If and Else C# Switch Statements C# While and Do-While Loops C# For Loops C# Nested Loops C# Methods - Part 1 (Basics) C# Methods - Part 2 (ref, out, and Recursion) C# Arrays C# Number Systems (Binary and Hexadecimal) C# Exception Handling (Try-Catch) C# Random Numbers C# String Methods and Manipulation C# Course Summary and Best Practices


C# Variables and Data Types

What is a Variable?

A variable is a container that stores data values. Think of it as a labeled box where you can store information.

int age = 25;           // Stores a whole number
string name = "John";   // Stores text
double price = 19.99;   // Stores decimal numbers

C# Data Types

Numeric Types

Integer Types (Whole Numbers)

Type Size Range Example
int 4 bytes -2,147,483,648 to 2,147,483,647 int iAge = 25;
long 8 bytes Very large numbers long lPopulation = 7800000000;
short 2 bytes -32,768 to 32,767 short sYear = 2025;
byte 1 byte 0 to 255 byte bValue = 100;

Floating-Point Types (Decimal Numbers)

Type Size Precision Example
float 4 bytes 6-7 digits float fPrice = 19.99f;
double 8 bytes 15-16 digits double dPrice = 19.99;
decimal 16 bytes 28-29 digits decimal mMoney = 19.99m;

Important Notes: - Use f suffix for float: float fValue = 3.14f; - Use m suffix for decimal: decimal mPrice = 99.99m; - double is the default for decimal numbers

Other Common Types

Type Description Example
char Single character char cGrade = 'A';
string Text/sequence of characters string sName = "John";
bool True or false bool isValid = true;

Naming Conventions (Hungarian Notation)

Based on your course requirements, use these prefixes:

// Integer
int iCount = 0;
int iNumber = 100;

// Double
double dPrice = 19.99;
double dAverage = 85.5;

// String
string sName = "Alice";
string sMessage = "Hello";

// Char
char cGrade = 'A';
char cOperator = '+';

// Boolean
bool isValid = true;
bool isEmployed = false;

// Decimal (for money)
decimal mSalary = 50000.00m;
decimal mPrice = 199.99m;

// Float
float fTemperature = 36.5f;

Declaring and Initializing Variables

Declaration Only

int iAge;           // Declared but not initialized
string sName;       // Declared but not initialized

Declaration with Initialization

int iAge = 25;                    // Declared and initialized
string sName = "Alice";           // Declared and initialized
double dPrice = 19.99;            // Declared and initialized

Multiple Declarations

// Same type, separate lines
int iA = 5;
int iB = 10;
int iC = 15;

// Same type, one line
int iX = 1, iY = 2, iZ = 3;

// Multiple variables, initialize later
int iCount, iSum, iTotal;
iCount = 0;
iSum = 0;
iTotal = 0;

Constants

Constants are variables whose values cannot be changed after initialization.

const double PI = 3.14159;
const int MAX_STUDENTS = 100;
const string UNIVERSITY = "University of Free State";

// PI = 3.14;  // ERROR! Cannot change a constant

Type Conversion

Implicit Conversion (Automatic)

int iNum = 10;
double dNum = iNum;    // int to double (automatic)

Explicit Conversion (Casting)

double dPrice = 19.99;
int iPrice = (int)dPrice;      // Result: 19 (decimals lost)

// Another example
double dValue = 10.75;
int iValue = (int)dValue;      // Result: 10

Using Convert Class

// String to int
string sAge = "25";
int iAge = Convert.ToInt32(sAge);

// String to double
string sPrice = "19.99";
double dPrice = Convert.ToDouble(sPrice);

// Int to string
int iNumber = 100;
string sNumber = iNumber.ToString();

Parse Methods

// String to int
int iAge = int.Parse("25");

// String to double
double dPrice = double.Parse("19.99");

// String to decimal
decimal mSalary = decimal.Parse("50000.50");

// String to char
char cGrade = char.Parse("A");

Practical Examples from Your Course

Example 1: Basic Variables

using System;

namespace VariablesDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare variables
            string sName;
            int iAge;
            double dHeight;

            // Get input from user
            Console.Write("Enter your name: ");
            sName = Console.ReadLine();

            Console.Write("Enter your age: ");
            iAge = int.Parse(Console.ReadLine());

            Console.Write("Enter your height (in meters): ");
            dHeight = double.Parse(Console.ReadLine());

            // Display output
            Console.WriteLine("\n--- Your Information ---");
            Console.WriteLine("Name: " + sName);
            Console.WriteLine("Age: " + iAge);
            Console.WriteLine("Height: " + dHeight + "m");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}

Example 2: Calculations (Stock Trading)

From Practical Test 2 - CSIQ1533:

using System;

namespace StockCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declare variables
            int iShares = 1000;
            decimal mPurchasePrice = 599.92m;
            decimal mSellPrice = 619.09m;
            double dCommission = 0.02;  // 2%

            // Calculate amounts
            decimal mPurchaseAmount = iShares * mPurchasePrice;
            decimal mBuyCommission = mPurchaseAmount * (decimal)dCommission;

            decimal mSellAmount = iShares * mSellPrice;
            decimal mSellCommission = mSellAmount * (decimal)dCommission;

            decimal mProfit = (mSellAmount - mSellCommission) - 
                             (mPurchaseAmount + mBuyCommission);

            // Display results
            Console.WriteLine("Stock Trading Summary");
            Console.WriteLine("=====================");
            Console.WriteLine("Purchase Amount: " + mPurchaseAmount.ToString("C"));
            Console.WriteLine("Buy Commission: " + mBuyCommission.ToString("C"));
            Console.WriteLine("Sell Amount: " + mSellAmount.ToString("C"));
            Console.WriteLine("Sell Commission: " + mSellCommission.ToString("C"));
            Console.WriteLine("Total Profit: " + mProfit.ToString("C"));

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}

String Formatting

Using ToString()

double dValue = 123.456;

Console.WriteLine(dValue.ToString("0.00"));    // 123.46
Console.WriteLine(dValue.ToString("0.0"));     // 123.5
Console.WriteLine(dValue.ToString("F2"));      // 123.46
Console.WriteLine(dValue.ToString("F4"));      // 123.4560

decimal mMoney = 1234.56m;
Console.WriteLine(mMoney.ToString("C"));       // $1,234.56 (currency)

Using String.Format()

string sName = "Alice";
int iAge = 25;
string sMessage = String.Format("My name is {0} and I am {1} years old", sName, iAge);
Console.WriteLine(sMessage);

Using String Interpolation

string sName = "Bob";
int iAge = 30;
Console.WriteLine($"My name is {sName} and I am {iAge} years old");

Practice Exercises

Exercise 1: Temperature Converter

Create a program that converts Celsius to Fahrenheit. Formula: F = (9.0 / 5) * C + 32

Exercise 2: Hexagon Area

Calculate the area of a hexagon given the side length. Formula: Area = (3 * √3 / 2) * s²

Exercise 3: Distance Calculator

Calculate distance between two points (x1, y1) and (x2, y2). Formula: √((x2 - x1)² + (y2 - y1)²)

Common Mistakes to Avoid

Forgetting type suffixes:

float fValue = 3.14;    // WRONG! Needs 'f'
float fValue = 3.14f;   // CORRECT

Wrong naming convention:

int count = 0;          // WRONG! Missing prefix
int iCount = 0;         // CORRECT

Type mismatch:

int iValue = 10.5;      // WRONG! Can't assign double to int
double dValue = 10.5;   // CORRECT

Key Takeaways

✅ Variables store data values ✅ Choose the right data type for your data ✅ Use Hungarian notation (prefixes) for naming ✅ Use ToString() for formatting output ✅ Use Parse() or Convert for type conversion ✅ Always initialize variables before using them ✅ Use decimal for money calculations


Next Topic: C# Console Input and Output