The Power of C#: From Basic Data Types to Advanced Control Flow
Learn how to use arrays, operators, and loops to solve real-world problems in C#.
C# (pronounced C-Sharp) is a modern, object-oriented programming language developed by Microsoft in the early 2000s. It is part of the .NET ecosystem and is widely used for building various types of applications, including web, desktop, mobile, and cloud-based solutions.
1. Key Features of C#
- Object-Oriented: Supports principles like encapsulation, inheritance, and polymorphism.
- Strongly Typed: Enforces strict type checking to prevent errors.
- Garbage Collection: Automatically manages memory to reduce memory leaks.
- Cross-Platform Development: Supports Windows, macOS, and Linux through .NET Core/.NET 5+.
- Interoperability: Can work with other languages, including C++ and F#.
- Asynchronous Programming: Uses
async
andawait
for non-blocking operations. - Secure and Scalable: Provides features like exception handling and access modifiers.
2. Common Uses of C#
- Desktop Applications: Using Windows Forms (WinForms) and Windows Presentation Foundation (WPF).
- Web Development: With ASP.NET Core for creating web applications and APIs.
- Mobile Apps: Using Xamarin or .NET MAUI to build cross-platform applications.
- Game Development: With Unity Engine, one of the most popular game development platforms.
- Cloud & Enterprise Applications: Through Azure and microservices architectures.
3. Basic C# Example
Here’s a simple “Hello, World!” program in C#
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
4. Standard Input and Output
C# provides various ways to handle standard input (stdin) and standard output (stdout) using the System.Console
class.
Standard Output
Console.Write()
: Prints text without moving to the next line.Console.WriteLine()
: Prints text and moves to the next line.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!"); // Prints with a newline
Console.Write("Enter your name: "); // Prints without a newline
}
}
Standard Input
Console.ReadLine()
reads a full line as astring
.
using System;
class Program
{
static void Main()
{
Console.Write("Enter your name: ");
string name = Console.ReadLine(); // Reads the entire line
Console.WriteLine("Hello, " + name + "!");
}
}
- If you need to read numbers, you must convert them.
int age = int.Parse(Console.ReadLine());
// Alternative
int age = Convert.ToInt32(Console.ReadLine());
Reading a Single Character
Console.Read()
reads a single character as anint
(ASCII value).
char character = (char) Console.Read();
Console.WriteLine("Character: " + character);
Formatting Output
- C# allows formatted printing using placeholders
{}
.
using System;
class Program
{
static void Main()
{
string name = "Alice";
int age = 25;
Console.WriteLine("Name: {0}, Age: {1}", name, age);
// Using string interpolation
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
5. Data Types
C# has two main categories of data types
Value Types
: Stored directly in memory.Reference Types
: Store references (memory addresses) to the actual data.
Value Types
- Store actual values.
- Stored in the stack memory.
- When assigned to another variable, a copy of the value is made.
- Examples:
int
,float
,char
,bool
,struct
,enum
.
int num1 = 10;
int num2 = num1; // num2 gets a COPY of num1's value
num1 = 20; // Changes num1, but num2 remains 10
Console.WriteLine(num1); // Output: 20
Console.WriteLine(num2); // Output: 10
Reference Types
- Store a reference (memory address) instead of the actual value.
- Stored in the heap memory.
- When assigned to another variable, both variables point to the same memory location.
- Examples:
class
,string
,object
,array
,interface
,delegate
.
class Person
{
public string Name;
}
Person p1 = new Person();
p1.Name = "John";
Person p2 = p1; // p2 points to the same object in heap memory
p2.Name = "Alice"; // Changing p2 also changes p1
Console.WriteLine(p1.Name); // Output: Alice
Console.WriteLine(p2.Name); // Output: Alice
6. Boxing and Unboxing
Boxing and unboxing are mechanisms that allow conversion between value types and reference types in C#. They are used when storing value types in objects or extracting them back.
Boxing (Value Type → Object)
- Converting a value type (
int
,double
,char
, etc.) into an object (reference type). - The value type (stack) is moved to the heap inside an object.
- Involves memory allocation and copying, making it slower than direct value type operations.
int num = 10; // Value type (stored in stack)
object obj = num; // Boxing: num is wrapped inside an object (stored in heap)
Console.WriteLine(obj); // Output: 10
num
is anint
(value type).obj
storesnum
as an object (reference type).
Unboxing (Object → Value Type)
- Extracting a value type from an object (reference type).
- The value is retrieved from the heap and copied back to the stack.
- Can cause exceptions if the cast is incorrect.
object obj = 10; // Boxing
int num = (int) obj; // Unboxing: Extracting int from object
Console.WriteLine(num); // Output: 10
- The object
obj
holds anint
(10). num = (int)obj;
converts the object back to anint
.
7. Operators
Operators in C# are symbols used to perform operations on variables and values. C# provides various types of operators.
Arithmetic Operators
- Function: Perform mathematical operations.
- Symbols:
+
,-
,*
,/
,%
- Example:
a + b
,a * b
Assignment Operators
- Function: Assign values to variables.
- Symbols:
=
,+=
,-=
,*=
,/=
,%=
,&=
,|=
,^=
,<<=
,>>=
- Example:
x += 5
(Equivalent tox = x + 5
)
Comparison (Relational) Operators
- Function: Compare values and return
true
orfalse
. - Symbols:
==
,!=
,>
,<
,>=
,<=
- Example:
a > b
,x == y
Logical Operators
- Function: Perform logical operations and return
true
orfalse
. - Symbols:
&&
,||
,!
- Example:
(a > b) && (c < d)
Bitwise Operators
- Function: Perform bit-level operations on integer values.
- Symbols:
&
,|
,^
,~
,<<
,>>
- Example:
a & b
,a << 2
Increment & Decrement Operators
- Function: Increase or decrease the value of a variable.
- Symbols:
++
,--
- Example:
++x
,x--
Ternary Operator
- Function: Shorten
if-else
statements. - Symbol:
? :
- Example:
result = (a > b) ? "A is greater" : "B is greater";
Null-Coalescing Operators
- Function: Handle
null
values safely. - Symbols:
??
- Example:
name = userName ?? "Guest";
Type Cast Operators
- Function: Convert between different data types.
- Symbols:
(type)
- Example:
int num = (int)doubleValue;
8. Decision-Making
Decision-making structures allow a program to execute different code blocks based on conditions. C# provides the following decision-making statements.
if
Statement
- Executes a block of code if a condition is
true
.
int num = 10;
if (num > 5)
{
Console.WriteLine("Number is greater than 5");
}
if-else
Statement
- Executes one block if the condition is
true
, otherwise executes another block.
int age = 18;
if (age >= 18)
{
Console.WriteLine("Eligible to vote");
}
else
{
Console.WriteLine("Not eligible to vote");
}
if-else if-else
Statement
- Checks multiple conditions sequentially.
int marks = 85;
if (marks >= 90)
{
Console.WriteLine("Grade: A");
}
else if (marks >= 75)
{
Console.WriteLine("Grade: B");
}
else
{
Console.WriteLine("Grade: C");
}
switch
Statement
- Used when multiple possible values need to be checked for a variable.
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
switch
Expression (C# 8.0 and later)
- A modern way to write
switch
statements more concisely.
int num = 2;
string result = num switch
{
1 => "One",
2 => "Two",
3 => "Three",
_ => "Unknown Number"
};
Console.WriteLine(result);
9. Loops
Loops allow you to execute a block of code multiple times, depending on a condition. C# provides several types of loops to handle different situations.
for
Loop
- The
for
loop is used when the number of iterations is known beforehand.
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
while
Loop
- The
while
loop is used when you want to repeat a block of code as long as the condition istrue
. The condition is evaluated before the execution.
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
do..while
Loop
- The
do..while
loop guarantees that the code block is executed at least once, even if the condition isfalse
. The condition is checked after each iteration.
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
foreach
Loop
- The
foreach
loop is used to iterate over a collection (like arrays, lists, etc.). It simplifies iterating through collections without needing to manage an index.
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
10. Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations. C# provides different types of arrays.
One-Dimensional Array
- A simple list-like structure where elements are stored in a single row.
int[] numbers = new int[5]; // Declare an array of size 5
numbers[0] = 10; // Assign values
numbers[1] = 20;
int[] arr = { 10, 20, 30, 40, 50 }; // Declare & initialize
foreach (int num in arr)
{
Console.WriteLine(num);
}
Multi-Dimensional (Rectangular) Array
- A rectangular array has fixed rows and columns like a matrix. All rows have the same number of columns.
int[,] matrix = new int[2, 3]; // 2 rows, 3 columns
matrix[0, 0] = 1;
matrix[1, 2] = 5;
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } }; // Declare & initialize
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
Jagged Array
- A jagged array is an array of arrays, where each row can have different lengths.
int[][] jagged = new int[3][]; // Declare with 3 rows
jagged[0] = new int[] { 1, 2, 3 };
jagged[1] = new int[] { 4, 5 };
jagged[2] = new int[] { 6, 7, 8, 9 };
int[][] jaggedArray =
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
for (int i = 0; i < jaggedArray.Length; i++)
{
foreach (int num in jaggedArray[i])
{
Console.Write(num + " ");
}
Console.WriteLine();
}
Practical Questions
- Write a program that takes an array of integers and finds the largest number in the array.
- Create a program that takes an array of integers and calculates the average of all the numbers in the array.
- Create a program that takes a list of integers and prints out the smallest even number in the array.
- Write a program that accepts an array of integers and prints all the prime numbers in the array.
- Write a program that counts how many times a specific number appears in an array.
- Write a program that checks if an array of integers forms a palindrome (i.e., the array reads the same backward and forward).
- Write a program that checks if one array is a subset of another array.