
Welcome to our C# Full Course for beginners with Dr. Zeeshan Bhatti.! In this series, we’ll cover all the fundamental aspects of C# programming language. Whether you’re a beginner or need a refresher, this tutorial will provide a comprehensive overview of C#. Let’s get started!
- 2. Why Learn C#
- 3. C# Intro
- 4. C# Get Started
- 5. C# Syntax
- 6. C# Output
- 7. C# Comments
- 8. C# Variables
- 9. C# Data Types
- 10. C# Type Casting
- 11. C# User Input
- 12. C# Operators
- 13. C# Math
- 14. C# Strings
- 15. C# Booleans
- 16. C# If…Else, Nested If-Else
- 17. C# Switch
- 18. C# While Loop
- 19. C# For Loop
- 20. C# For-each loop
- 21. C# Break/Continue
- 22. C# Arrays
- 23. C# Methods
- 24. C# Methods
- 25. C# Method Parameters
- 26. C# Method Overloading
- 27. C# Classes
- 28. C# OOP
- 29. C# Classes/Objects
- 30. C# Class Members
- 31. C# Constructor
- Conclusion
2. Why Learn C#
C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET Framework.
C# is used to develop web apps, desktop apps, mobile apps, games and much more
- C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET initiative.
- It is one of the most popular programming languages in the world
- It is easy to learn and simple to use
- It has huge community support
- C# is an object-oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs
- As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa
- It’s widely used for developing Windows applications, web services, and games using Unity. We’ll dive into the details in the following sections.
3. C# Intro
It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.
C# has roots from the C family, and the language is close to other popular languages like C++ and Java.
The first version was released in year 2002.
C# is designed to be simple, modern, and flexible. It’s influenced by C++ and Java, making it easier for developers familiar with these languages to pick up C#. In this section, we’ll discuss what makes C# unique and its primary features.
Consider C# as a language that combines the power of C++ with the simplicity of Java. It supports strong typing, object-oriented programming, and component-oriented programming.
Real-World Problem:
Problem: Develop a simple Windows application.
Solution: Use Visual Studio to create a Windows Forms application.
4. C# Get Started
To get started with C#, you need to install Visual Studio, a powerful IDE by Microsoft. In this section, we’ll guide you through setting up your development environment and writing your first C# program.
Example:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(“Hello, World!”);
}
}
}
Real-World Problem:
Problem: Set up a development environment for C#.
Solution: Install Visual Studio Community Edition and create a new Console Application.
5. C# Syntax
C# syntax is similar to other C-based languages, making it easy to learn for those with prior experience. We’ll cover the basics of C# syntax, including namespaces, classes, methods, and statements.
Example:
using System;
namespace ExampleNamespace
{
class ExampleClass
{
static void ExampleMethod()
{
Console.WriteLine(“This is an example method.”);
}
}
}
Line 1: using System means that we can use classes from the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more readable.
Line 3: namespace is used to organize your code, and it is a container for classes and other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to your program. Every line of code that runs in C# must be inside a class. In our example, we named the class Program.
Don’t worry if you don’t understand how using System, namespace and class works. Just think of it as something that (almost) always appears in your program, and that you will learn more about them in a later chapter.
Line 7: Another thing that always appear in a C# program is the Main method. Any code inside its curly brackets {} will be executed. You don’t have to understand the keywords before and after Main. You will get to know them bit by bit while reading this tutorial.
Line 9: Console is a class of the System namespace, which has a WriteLine() method that is used to output/print text. In our example, it will output “Hello World!”.
If you omit the using System line, you would have to write System.Console.WriteLine() to print/output text.
Note: Every C# statement ends with a semicolon ;.
Note: C# is case-sensitive; “MyClass” and “myclass” have different meaning.
Note: Unlike Java, the name of the C# file does not have to match the class name, but they often do (for better organization). When saving the file, save it using a proper name and add “.cs” to the end of the filename.
Real-World Problem:
Problem: Write a method that prints a message to the console.
Solution: Implement the ExampleMethod as shown above.
6. C# Output
In this section, we’ll learn how to produce output in C#. The most common way to output text is using the Console.WriteLine method.
Example:
Console.WriteLine(“This is an output example.”);
Real-World Problem:
Problem: Display a welcome message to the user.
Solution: Use Console.WriteLine(“Welcome to C# programming!”);.
7. C# Comments
Comments are essential for making your code readable and maintainable. C# supports single-line (//) and multi-line (/* */) comments.
Example:
// This is a single-line comment
/*
This is a
multi-line comment
*/
Real-World Problem:
Problem: Add comments to describe the functionality of your methods.
Solution: Use single-line and multi-line comments appropriately in your code.
8. C# Variables
a. C# Variables
Variables are used to store data in a program. C# is a strongly-typed language, meaning you need to declare the type of a variable before using it.
Example:
int age = 30;
string name = “John”;
Real-World Problem:
Problem: Store and display a user’s age and name.
Solution: Use int age and string name as shown above.
b. Constants
Constants are immutable values which are known at compile-time and do not change for the life of the program.
Example:
const double PI = 3.14159;
Real-World Problem:
Problem: Define a constant for the value of Pi.
Solution: Use const double PI = 3.14159;.
c. Multiple Variables
You can declare multiple variables of the same type in a single statement.
Example:
int a = 1, b = 2, c = 3;
Real-World Problem:
Problem: Declare and initialize multiple variables in a single line.
Solution: Use int a = 1, b = 2, c = 3;.
9. C# Data Types
C# provides a rich set of data types. These include primitive types like int, double, and char, as well as complex types like arrays and objects.
Example:
int number = 100;
double pi = 3.14;
char letter = ‘A’;
string message = “Hello, World!”;
Real-World Problem:
Problem: Store different types of data in variables.
Solution: Use appropriate data types like int, double, char, and string.
10. C# Type Casting
Type casting is converting one data type to another. In C#, you can use both implicit and explicit casting.
Example:
// Implicit casting
int i = 100;
double d = i;
// Explicit casting
double pi = 3.14;
int intPi = (int)pi;
Real-World Problem:
Problem: Convert a double to an integer.
Solution: Use explicit casting like int intPi = (int)pi;.
11. C# User Input
C# provides the Console.ReadLine method to get user input from the console.
Example:
Console.WriteLine(“Enter your name:”);
string name = Console.ReadLine();
Console.WriteLine(“Hello, ” + name);
Real-World Problem:
Problem: Ask the user for their name and greet them.
Solution: Use Console.ReadLine to read input and Console.WriteLine to display the greeting.
12. C# Operators
a. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. These include +, -, *, /, and %.
Example:
int sum = 5 + 3;
int difference = 5 – 3;
int product = 5 * 3;
int quotient = 5 / 3;
int remainder = 5 % 3;
Real-World Problem:
Problem: Calculate the sum, difference, product, quotient, and remainder of two numbers. Solution: Use the arithmetic operators as shown above.
b. Assignment Operators
Assignment operators are used to assign values to variables. The most common is =.
Example:
int x = 10;
x += 5; // x = x + 5
x -= 3; // x = x – 3
Real-World Problem:
Problem: Increment and decrement a variable’s value.
Solution: Use += and -= operators.
c. Comparison Operators
Comparison operators are used to compare values. These include ==, !=, >, <, >=, and <=.
Example:
int a = 5;
int b = 3;
bool isEqual = (a == b);
bool isNotEqual = (a != b);
bool isGreater = (a > b);
bool isLesser = (a < b);
Real-World Problem:
Problem: Compare two numbers to see if they are equal or which one is greater.
Solution: Use the comparison operators as shown above.
d. Logical Operators
Logical operators are used to combine multiple conditions. These include && (AND), || (OR), and ! (NOT).
Example:
bool isAdult = (age >= 18) && (age <= 65);
bool isTeenager = (age >= 13) && (age <= 19);
bool isNotAdult = !isAdult;
Real-World Problem:
Problem: Determine if a person is an adult or a teenager.
Solution: Use the logical operators as shown above.
13. C# Math
The Math class in C# provides methods for performing mathematical operations like rounding, finding the square root, and calculating powers.
Example:
double squareRoot = Math.Sqrt(16);
double power = Math.Pow(2, 3);
double rounded = Math.Round(3.14159, 2);
Real-World Problem:
Problem: Calculate the square root and power of numbers.
Solution: Use Math.Sqrt and Math.Pow methods.
14. C# Strings
Strings in C# are used to store text. The string class provides various methods for string manipulation like Substring, Replace, and ToUpper.
Example:
string text = “Hello, World!”;
string upperText = text.ToUpper();
string substring = text.Substring(0, 5);
Real-World Problem:
Problem: Convert a string to uppercase and extract a substring.
Solution: Use ToUpper and Substring methods.
15. C# Booleans
Boolean variables can hold true or false values. They are often used in conditional statements and loops.
Example:
bool isRaining = true;
bool isSunny = false;
Real-World Problem:
Problem: Store and use boolean values in a condition.
Solution: Use boolean variables as shown above.
16. C# If…Else, Nested If-Else
If-else statements are used for decision-making in C#. Nested if-else statements allow for multiple conditions to be checked sequentially.
Example:
if (age < 13)
{
Console.WriteLine(“You are a child.”);
}
else if (age < 18)
{
Console.WriteLine(“You are a teenager.”);
}
else
{
Console.WriteLine(“You are an adult.”);
}
Real-World Problem:
Problem: Classify a person based on their age.
Solution: Use nested if-else statements as shown above.
17. C# Switch
The switch statement is an alternative to using multiple if statements. It is used to execute one out of multiple possible blocks of code.
Example:
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(“Other day”);
break;
}
Real-World Problem:
Problem: Print the name of the day based on its number.
Solution: Use a switch statement as shown above.
18. C# While Loop
The while loop repeatedly executes a block of code as long as the specified condition is true.
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
Real-World Problem:
Problem: Print numbers from 0 to 4 using a loop.
Solution: Use a while loop as shown above.
19. C# For Loop
The for loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and iteration.
Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Real-World Problem:
Problem: Print numbers from 0 to 4 using a for loop.
Solution: Use a for loop as shown above.
20. C# For-each loop
The foreach loop iterates over each element in a collection, such as an array or a list
Example:
string[] fruits = { “Apple”, “Banana”, “Cherry” };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Real-World Problem:
Problem: Print all elements in an array.
Solution: Use a foreach loop as shown above.
21. C# Break/Continue
The break statement terminates the loop, while the continue statement skips the current iteration and moves to the next one.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
break;
if (i % 2 == 0)
continue;
Console.WriteLine(i);
}
Real-World Problem:
Problem: Print odd numbers less than 10 but stop if the number is 5.
Solution: Use break and continue statements as shown above.
22. C# Arrays
Arrays are used to store multiple values of the same type in a single variable. C# supports both single-dimensional and multi-dimensional arrays.
Example:
int[] numbers = { 1, 2, 3, 4, 5 };
int[,] matrix = { { 1, 2 }, { 3, 4 } };
Real-World Problem:
Problem: Store a list of numbers and a 2×2 matrix.
Solution: Use single-dimensional and multi-dimensional arrays as shown above.
23. C# Methods
Methods are blocks of code that perform a specific task. They help in reusing code and making the program modular.
Example:
void Greet()
{
Console.WriteLine(“Hello!”);
}
Real-World Problem:
Problem: Create a method to print a greeting message.
Solution: Define a method Greet as shown above.
24. C# Methods
Methods can take parameters and return values, making them more versatile.
Example:
int Add(int a, int b)
{
return a + b;
}
Real-World Problem:
Problem: Create a method to add two numbers and return the result.
Solution: Define the Add method as shown above.
25. C# Method Parameters
Methods can accept parameters to work with different values. Parameters can be passed by value or by reference.
Example:
void PrintSum(int a, int b)
{
Console.WriteLine(a + b);
}
Real-World Problem:
Problem: Create a method that takes two parameters and prints their sum.
Solution: Define the PrintSum method as shown above.
26. C# Method Overloading
Method overloading allows multiple methods with the same name but different parameters in the same class.
Example:
void Display(int a)
{
Console.WriteLine(a);
}
void Display(string message)
{
Console.WriteLine(message);
}
Real-World Problem:
Problem: Create overloaded methods to display an integer and a string.
Solution: Define the Display method with different parameter types as shown above.
27. C# Classes
Classes are the blueprint for creating objects. They encapsulate data and behavior. In C#, classes are defined using the class keyword.
Example:
class Person
{
public string Name;
public int Age;
public void Greet()
{
Console.WriteLine(“Hello, ” + Name);
}
}
Real-World Problem:
Problem: Create a class to represent a person with a name and age, and a method to greet. Solution: Define the Person class as shown above.
28. C# OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects. C# supports OOP principles like encapsulation, inheritance, and polymorphism.
Example:
class Animal
{
public void Speak()
{
Console.WriteLine(“The animal makes a sound.”);
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine(“The dog barks.”);
}
}
Real-World Problem:
Problem: Implement inheritance by creating a Dog class that inherits from Animal.
Solution: Define the Animal and Dog classes as shown above.
29. C# Classes/Objects
Objects are instances of classes. They are created using the new keyword.
Example:
Person person = new Person();
person.Name = “John”;
person.Age = 30;
person.Greet();
Real-World Problem:
Problem: Create an object of the Person class and call its methods.
Solution: Instantiate the Person class and use its members as shown above.
30. C# Class Members
Class members include fields, properties, methods, and events. Fields are variables within a class. Properties provide a way to read and write data.
Example:
class Car
{
public string Model { get; set; }
public int Year { get; set; }
}
Real-World Problem:
Problem: Define a class with properties for a car’s model and year.
Solution: Define the Car class with properties as shown above.
31. C# Constructor
Constructors are special methods called when an object is instantiated. They initialize the object’s state.
Example:
class Book
{
public string Title;
public string Author;
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
Real-World Problem:
Problem: Create a Book class with a constructor to initialize the title and author.
Solution: Define the Book class with a constructor as shown above.