Source: 1.Intro_To_CSharp.pdf

Introduction to C#

Syntax, variables, data types, type casting, user input, operators, strings, control flow, loops, arrays, and methods.

Program Structure and Syntax

Every C# program starts from Main(). Code lives inside classes, statements end with semicolons, and C# is case-sensitive — Console.WriteLine is not the same as console.writeline.

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Output

Hello, World!

Syntax — Exercise 1

Fix the broken starter program, then answer the concept question.

Fix all syntax errors in the program

Hint

C# is case-sensitive. Check the capitalization of Console and WriteLine, and add a semicolon after each statement.

What character ends every statement in C#?

Syntax — Exercise 2

Single-line comments use //. Multi-line comments use /* */. Neither affects execution.

Uncomment the correct line and fix the second statement

Hint

Remove the // before the first WriteLine. Fix the capitalisation of the second one and add a semicolon.

Variables and Constants

Variables store values that can change. Use const for compile-time constants that never change. var lets the compiler infer the type from the assigned value.

csharp
int age = 25;
string name = "Alice";
const double Pi = 3.14159;
var score = 100;          // inferred as int

Console.WriteLine(name + " is " + age);
Console.WriteLine("Pi = " + Pi);
Console.WriteLine("Score: " + score);

Output

Alice is 25
Pi = 3.14159
Score: 100

Variables — Exercise 1

const values are fixed at compile time and cannot be reassigned. Trying to do so causes a compile error.

Fix the illegal const reassignment

Hint

Remove const to make max a regular variable that can be reassigned.

Which keyword creates a value that cannot be changed after declaration?

Variables — Exercise 2

Once var infers a type, that type is locked. You cannot assign a value of a different type to the same variable.

Fix the var type mismatch

Hint

var infers int from the literal 10. You cannot later assign a string to it.

Data Types

C# has value types (int, double, bool, char) and reference types (string, arrays, objects). Value types hold data directly; reference types hold a memory address.

csharp
int count = 5;
double price = 9.99;
bool isActive = true;
char grade = 'A';
string message = "Hello";

Console.WriteLine($"{count}, {price}, {isActive}, {grade}, {message}");

Output

5, 9.99, True, A, Hello

Data Types — Exercise 1

char uses single quotes for a single character. string uses double quotes for text. Mixing them is a compile error.

Fix the mismatched quote styles

Hint

char uses single quotes ('A'). string uses double quotes ("Hi").

What is the default value of an uninitialized int field in C#?

Type Casting

Implicit casting converts to a larger compatible type automatically (int → double). Explicit casting uses a cast operator (int) and may lose precision.

csharp
int myInt = 9;
double myDouble = myInt;        // implicit: no data loss

double price = 19.75;
int rounded = (int)price;       // explicit: decimal is truncated

Console.WriteLine(myDouble);
Console.WriteLine(rounded);

Output

9
19

Type Casting — Exercise 1

You cannot cast a string directly to a numeric type with (). Use int.Parse() or Convert.ToInt32() instead.

Fix the invalid string-to-int cast

Hint

Use int.Parse() or Convert.ToInt32() to convert a string to an integer.

Which conversion requires an explicit cast operator in C#?

User Input

Console.ReadLine() reads a line of text and always returns a string. Convert it to a number with int.Parse() or Convert.ToInt32() before arithmetic.

csharp
Console.Write("Enter your name: ");
string name = Console.ReadLine();

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

Console.WriteLine($"Hello {name}, you are {age} years old.");

Output

Enter your name: Alice
Enter your age: 30
Hello Alice, you are 30 years old.

User Input — Exercise 1

Console.ReadLine() returns string, not int. You must parse it before using it in arithmetic.

Fix the missing parse call

Hint

Console.ReadLine() returns a string. Wrap it with int.Parse() to convert to int.

What type does Console.ReadLine() return?

Operators

C# supports arithmetic (+, -, *, /, %), comparison (==, !=, <, >), logical (&&, ||, !), and compound assignment (+=, -=, *=) operators.

csharp
int a = 10, b = 3;

Console.WriteLine(a + b);           // 13
Console.WriteLine(a / b);           // 3  (integer division)
Console.WriteLine(a % b);           // 1  (remainder)
Console.WriteLine(a > b);           // True
Console.WriteLine(a == 10 && b < 5); // True

Output

13
3
1
True
True

Operators — Exercise 1

When both operands are int, / performs integer division and drops the decimal. Cast one to double for a decimal result.

Fix integer division to produce 3.5

Hint

Change a and b to double so the division produces a decimal result.

What does the % operator return?

Strings

Strings are immutable sequences of characters. Use string interpolation ($"") or concatenation (+) to combine them. Common members: Length, ToUpper(), ToLower(), Substring(), Contains(), Replace().

csharp
string name = "Alice";
string greeting = $"Hello, {name}!";

Console.WriteLine(greeting);
Console.WriteLine(name.Length);
Console.WriteLine(name.ToUpper());
Console.WriteLine(name.Contains("li"));
Console.WriteLine(name.Replace("Alice", "Bob"));

Output

Hello, Alice!
5
ALICE
True
Bob

Strings — Exercise 1

String interpolation requires a $ before the opening quote. Without it, the curly braces are printed as literal text.

Fix the missing $ for interpolation

Hint

Add $ before the opening quote to enable interpolation.

Which member returns the number of characters in a string?

Control Flow — if/else and switch

if/else branches on conditions. switch compares one value against multiple cases. In C#, each case must end with break — implicit fall-through is not allowed.

csharp
int score = 75;

if (score >= 90)
    Console.WriteLine("A");
else if (score >= 70)
    Console.WriteLine("B");
else
    Console.WriteLine("C");

string day = "Mon";
switch (day)
{
    case "Mon": Console.WriteLine("Monday"); break;
    case "Fri": Console.WriteLine("Friday"); break;
    default:    Console.WriteLine("Other");  break;
}

Output

B
Monday

Control Flow — Exercise 1

Each case in a C# switch must end with break, return, or goto. Omitting break is a compile error.

Fix the missing break statements in switch

Hint

Add break; after each case body.

Which keyword exits a switch case in C#?

Control Flow — Exercise 2

The ternary operator (condition ? trueValue : falseValue) is a concise alternative to if/else for simple assignments.

Fix the broken ternary expression

Hint

The ternary operator always needs both a true-value and a false-value separated by :

Loops — for, while, foreach

for loops are best when the count is known. while loops run while a condition holds. foreach iterates over every element of a collection without an index.

csharp
for (int i = 0; i < 3; i++)
    Console.WriteLine("for: " + i);

int n = 3;
while (n > 0)
{
    Console.WriteLine("while: " + n);
    n--;
}

int[] nums = { 10, 20, 30 };
foreach (int num in nums)
    Console.WriteLine("foreach: " + num);

Output

for: 0
for: 1
for: 2
while: 3
while: 2
while: 1
foreach: 10
foreach: 20
foreach: 30

Loops — Exercise 1

An off-by-one error makes a loop start or stop one step too early or too late.

Fix the loop to print 1 through 5

Hint

Starting at i = 0 would print 0 as well. Start at i = 1.

What does break do inside a loop?

Loops — Exercise 2

continue skips the rest of the current iteration and moves to the next one. It is useful to filter values inside a loop.

Print only even numbers (2, 4, 6, 8, 10) using continue

Hint

Replace break with continue to skip odd numbers instead of stopping the loop.

Arrays

Arrays hold a fixed number of elements of the same type. Declare with Type[], initialize inline with {} or with new Type[size]. Access elements via zero-based index.

csharp
int[] scores = { 85, 90, 78, 92 };
string[] names = new string[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Carol";

Console.WriteLine(scores[0]);
Console.WriteLine(scores.Length);

foreach (string n in names)
    Console.WriteLine(n);

Output

85
4
Alice
Bob
Carol

Arrays — Exercise 1

Array indices are zero-based. The last valid index is Length - 1. Accessing Length causes IndexOutOfRangeException.

Fix the index out-of-range error

Hint

The array has 3 elements: valid indices are 0, 1, and 2. Index 3 does not exist.

What property gives the number of elements in a C# array?

Methods

A method groups reusable code under a name. It has a return type (or void), a name, parameters in (), and a body in {}. Call it by name with matching arguments.

csharp
static int Add(int a, int b)
{
    return a + b;
}

static void Greet(string name)
{
    Console.WriteLine("Hello, " + name + "!");
}

Console.WriteLine(Add(3, 4));
Greet("Alice");

Output

7
Hello, Alice!

Methods — Exercise 1

A non-void method must always reach a return statement of the declared type. Omitting it causes a compile error.

Fix the missing return statement

Hint

A method declared as int must end with return <int value>;

What return type should a method use if it returns nothing?