Comprehensive C# Tutorial: From Basics to Advanced Concepts
Mastering C#: From Hello, World! to OOP and Beyond
Introduction
Hello I'm Harsh Mendapara. Welcome to my comprehensive C# tutorial, where I will cover everything from the basics to advanced concepts. Whether you're just starting with C# or looking to expand your knowledge, this guide is designed to help you learn and master the language.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("Hello, Harsh!");
}
}
This is a simple C# program that prints "Hello, World!" to the console. The Main method is the entry point of the program, and Console.WriteLine is used to output text to the console.
using System: Allows the use of classes from the System namespace.
class: Keyword to define a class. Program: Class name, serves as a blueprint for creating objects. Contains data members and methods.
static: Keyword indicating that an object is not required to access static members, saving memory.
void: Return type of the method, indicating it doesn't return any value.
Curly braces {}: Mark code blocks. class: Contains data and methods, every executable line must be within a class. In this example, named Program.
Main method: Entry point of the program, where code executes.
string[] args: Used for command-line arguments in C#. Allows passing values while running the program, accessible within the program.
Console.WriteLine(): Method from System namespace's Console class, used to output text.
Semicolon ; : Ends every C# statement.
C# Comments: Annotate your code for readability using single-line //
or multi-line /* */
comments.
Example:
// Single-line comment /* Multi-line comment */
C# Variables and Data Types:
C# Variables: Declare variables to store data temporarily.
C# Data Types: Integers, floating-point numbers, characters, strings, booleans, etc.
Example:
int age = 30;
double price = 19.99;
char grade = 'A';
string name = "John";
bool isStudent = true;
C# Type Casting:
- Convert data from one type to another using explicit or implicit type casting.
Example:
double num1 = 10.5;
int num2 = (int)num1; // Explicit casting
C# User Input:
- Accept input from the user during program execution using
Console.ReadLine()
.
- Accept input from the user during program execution using
Example:
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
C# Operators:
- Arithmetic, relational, logical, and assignment operators for manipulating data.
Example:
int a = 10, b = 5;
int sum = a + b;
C# Math:
- Perform mathematical operations using built-in functions in the
Math
class.
- Perform mathematical operations using built-in functions in the
Example:
double result = Math.Sqrt(25);
C# Strings:
- Manipulate strings using various methods and properties.
Example:
string greeting = "Hello, world!";
int length = greeting.Length;
- C# Booleans:
- Work with boolean values and logical expressions.
Example:
bool isTrue = true;
C# If...Else:
- Use conditional statements to make decisions in your code.
Example:
int age = 20;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
C# Switch:
- Use switch statements for multi-way branching based on a value.
Example:
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
// More cases...
}
C# While Loop:
- Execute a block of code repeatedly while a condition is true.
Example:
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
C# For Loop:
- Execute a block of code a fixed number of times.
Example:
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
C# Break/Continue:
- Use break to exit a loop prematurely, and continue to skip the rest of the current iteration and continue to the next iteration.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
break; // Exit the loop when i equals 5
if (i % 2 == 0)
continue; // Skip even numbers
Console.WriteLine(i);
}
C# Arrays:
- Store multiple values of the same type in a single variable.
Example:
int[] numbers = { 1, 2, 3, 4, 5 };
C# Methods:
- Encapsulate reusable code blocks into methods for better organization and reusability.
Example:
void PrintHello()
{
Console.WriteLine("Hello");
}
C# Method Parameters:
- Pass data to methods using parameters.
Example:
void Greet(string name)
{
Console.WriteLine("Hello, " + name);
}
C# Method Overloading:
- Define multiple methods with the same name but different parameter lists.
Example:
int Add(int x, int y)
{
return x + y;
}
double Add(double x, double y)
{
return x + y;
}
C# Classes:
- Define blueprints for creating objects with properties and methods.
Example:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
C# Classes:
Description: Defining blueprints for creating objects with properties and methods.
Example:
class Person { public string Name { get; set; } public int Age { get; set; } public void DisplayInfo() { Console.WriteLine("Name: " + Name + ", Age: " + Age); } }
C# Class Members:
Description: Exploring fields, properties, methods, and constructors within a class.
Example:
class Car { // Fields private string make; private string model; // Properties public string Make { get { return make; } set { make = value; } } public string Model { get { return model; } set { model = value; } } // Constructor public Car(string make, string model) { this.make = make; this.model = model; } // Method public void Start() { Console.WriteLine("The car is starting..."); } }
C# Constructors:
Description: Special methods used to initialize objects of a class.
Example:
class Person { public string Name { get; set; } public int Age { get; set; } // Constructor public Person(string name, int age) { Name = name; Age = age; } }
C# Access Modifiers:
Description: Control the accessibility of class members.
Example:
class BankAccount { private decimal balance; // Private field public void Deposit(decimal amount) { balance += amount; } public decimal GetBalance() { return balance; } }
C# Properties:
Description: Encapsulate fields and provide controlled access to them.
Example:
class Person { private string name; public string Name { get { return name; } set { name = value; } } }
C# Inheritance:
Description: Create new classes based on existing ones, inheriting their properties and behaviors.
Example:
class Animal { public void Eat() { Console.WriteLine("The animal is eating..."); } } class Dog : Animal { public void Bark() { Console.WriteLine("Woof! Woof!"); } }
C# Polymorphism:
Description: Achieve multiple forms of behavior using inheritance and method overriding.
Example:
class Shape { public virtual void Draw() { Console.WriteLine("Drawing a shape..."); } } class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing a circle..."); } }
C# Abstraction:
Description: Hide implementation details and show only essential features of an object.
Example:
abstract class Animal { public abstract void MakeSound(); } class Dog : Animal { public override void MakeSound() { Console.WriteLine("Woof! Woof!"); } }
C# Interface:
Description: Define contracts for classes to implement.
Example:
interface IShape { void Draw(); } class Circle : IShape { public void Draw() { Console.WriteLine("Drawing a circle..."); } }
C# Enums:
Description: Create named constants for a group of related values.
Example:
enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
File Input/Output Operations:
File input/output operations involve reading from and writing to files on disk. In C#, the System.IO
namespace provides classes and methods for working with files.
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Write text to a file
string text = "Hello, File!";
File.WriteAllText("example.txt", text);
// Read text from a file
string content = File.ReadAllText("example.txt");
Console.WriteLine("File content: " + content);
}
}
Explanation:
We use
File.WriteAllText()
to write text to a file named "example.txt". This method creates the file if it doesn't exist and overwrites its contents if it does.Then, we use
File.ReadAllText()
to read the contents of the "example.txt" file and store it in a string variable. Finally, we print the file content to the console.
Exception Handling:
Exception handling allows us to handle runtime errors gracefully, preventing our programs from crashing unexpectedly. In C#, exceptions are handled using try-catch-finally blocks.
using System;
class Program
{
static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Trying to access an out-of-bounds index
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
Console.WriteLine("End of program.");
}
}
}
Explanation:
We use a try block to contain the code that may raise an exception. In this example, we're trying to access an index outside the bounds of an array.
The catch blocks catch and handle specific types of exceptions. Here, we catch IndexOutOfRangeException if the array index is out of range and any other type of exception with the generic Exception catch block.
The finally block contains code that is executed regardless of whether an exception occurs. It's typically used for cleanup tasks or resource deallocation.
Conclusion:
Throughout this C# tutorial, we've covered everything from the basics to more advanced topics in a straightforward manner. From setting up your environment and writing your first program to diving into syntax, methods, and object-oriented programming principles, we've got you covered. We've also touched on handling files and dealing with errors gracefully through exception handling. With this knowledge, you're well-prepared to take on various software development tasks using C#. Keep practicing and building projects to strengthen your skills. Happy coding!