MD HASHIR IMTEYAZ
Console Program: Introduc on and Crea on
A console program is a text-based applica on that interacts with the user through the command line
or terminal. It does not rely on graphical user interfaces (GUIs) like windows or bu ons but instead
communicates with the user via text input and output. These programs are o en used for simple
tasks such as calcula ons, data processing, or system management.
Key Features of a Console Program:
1. Text-based interface: Interac on is done via keyboard inputs and textual output.
2. Minimal system resources: Console programs are lightweight and typically use less memory
and processing power.
3. Use of standard input/output: Input is received through the console, and output is printed
to the console.
Steps to Create a Basic Console Program in C#:
Write the Code: Here is an example of a simple console program that takes user input, performs a
basic opera on, and outputs the result:
using System;
namespace ConsoleApp
class Program
sta c void Main(string[] args)
Console.WriteLine("Welcome to the Console Program!");
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.Write("Please enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
int birthYear = DateTime.Now.Year - age;
Console.WriteLine($"Hello, {name}! You were born in {birthYear}.");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
Explana on of Code:
o Namespace: Organizes related classes.
o Console.WriteLine(): Displays output to the console.
o Console.ReadLine(): Reads input from the user.
o Convert.ToInt32(): Converts input into an integer.
o DateTime.Now.Year: Gets the current year for calcula on.
o Console.ReadKey(): Waits for a key press before closing the program.
Classes in C#
In C#, a class is a blueprint for crea ng objects (instances). It defines the proper es (variables),
methods (func ons), and events that an object can have. Classes are a core concept of Object-
Oriented Programming (OOP).
Key Concepts of a Class in C#:
1. Class Declara on: A class is declared using the class keyword, followed by the class name.
public class Car
// Proper es, methods, constructors, etc.
2. Proper es: Proper es hold the data of the object. In C#, proper es can have both get and
set accessors.
public class Car
public string Model { get; set; }
public string Color { get; set; }
public int Year { get; set; }
3. Methods: Methods define the behavior of the object. They can manipulate data or perform
ac ons.
public class Car
public void DisplayDetails()
{
Console.WriteLine($"Model: {Model}, Color: {Color}, Year: {Year}");
4. Constructors: Constructors ini alize the object when it is created.
public class Car
public string Model { get; set; }
public string Color { get; set; }
public int Year { get; set; }
public Car(string model, string color, int year)
Model = model;
Color = color;
Year = year;
5. Access Modifiers: Control the visibility and accessibility of class members.
o private: Accessible only within the same class.
o public: Accessible from anywhere.
o protected: Accessible within the class and derived classes.
o internal: Accessible within the same assembly (project).
o protected internal: Accessible within the same assembly and derived classes.
Example of Class with Proper es and Methods:
using System;
namespace CarExample
public class Car
public string Model { get; set; }
public string Color { get; set; }
public int Year { get; set; }
public Car(string model, string color, int year)
Model = model;
Color = color;
Year = year;
public void DisplayDetails()
Console.WriteLine($"Model: {Model}, Color: {Color}, Year: {Year}");
class Program
sta c void Main(string[] args)
Car myCar = new Car("Tesla Model S", "Red", 2023);
myCar.DisplayDetails();
Types of Members in a Class:
1. Fields: Variables that hold data for a class. Fields are o en private and accessed through
public proper es.
public class Car
{
private string model;
public string Model
get { return model; }
set { model = value; }
2. Methods: Func ons that define behavior or ac ons.
public class Car
public void StartEngine()
Console.WriteLine("The car engine has started.");
3. Events: Allow the class to no fy other parts of the program when an ac on occurs.
public class Car
public event EventHandler CarStarted;
public void StartCar()
CarStarted?.Invoke(this, EventArgs.Empty);
Different Types of Classes in C#:
1. Sta c Class:
o Cannot be instan ated.
o Contains only sta c members.
o Typically used for u lity func ons.
public sta c class MathHelper
public sta c int Add(int a, int b) => a + b;
public sta c int Mul ply(int a, int b) => a * b;
2. Sealed Class:
o Cannot be inherited.
o Can be instan ated.
o Used to prevent subclassing.
public sealed class FinalClass
public void DisplayMessage() => Console.WriteLine("This is a sealed class.");
3. Abstract Class:
o Cannot be instan ated.
o Can contain abstract methods, which must be implemented in derived classes.
public abstract class Animal
public abstract void MakeSound();
public void Eat() => Console.WriteLine("Ea ng food.");
public class Dog : Animal
public override void MakeSound() => Console.WriteLine("Bark!");
4. Normal Class:
o Can be instan ated.
o Contains both instance and sta c members.
public class Vehicle
{
public string Make { get; set; }
public string Model { get; set; }
public void Drive() => Console.WriteLine("Driving the vehicle.");
5. Interface:
o Defines a contract that classes must implement.
o Can contain method signatures but no implementa ons.
public interface IDriveable
void Drive();
public class Car : IDriveable
public void Drive() => Console.WriteLine("Car is driving.");
Object-Oriented Programming Concepts
1. Abstract Class
An abstract class cannot be instan ated and may contain abstract methods, which are
methods without implementa on. Derived classes are required to implement these abstract
methods.
Abstract classes help to provide a common interface for other classes and promote
reusability of code.
2. Polymorphism
Polymorphism allows a class or object to take on many forms. In C#, polymorphism can be
implemented through:
o Method Overloading: Defining mul ple methods with the same name but different
parameters.
o Method Overriding: A subclass provides a specific implementa on of a method
defined in its superclass.
Example of Method Overriding: A method in the base class can be overridden by a derived
class to provide more specific behavior.
3. Inheritance
Inheritance allows a class (derived class) to inherit proper es and behaviors (fields and
methods) from another class (base class).
The base class provides common func onality, while the derived class can extend or modify
that func onality.
Inheritance promotes code reuse and helps maintain a clear hierarchical structure.
4. Encapsula on
Encapsula on involves bundling data and methods that operate on that data into a single
unit (class).
It hides the internal data of the class and restricts direct access to it, ensuring that any
interac on with the data happens through public methods (ge ers and se ers).
This principle prevents unintended interference and misuse of the object's internal state.
Key Features of OOP:
Faster Execu on: Object-Oriented Programming is o en more efficient and easier to
execute.
Clear Structure: OOP promotes a clear and organized structure for programs, making them
easier to understand and manage.
Reusability: OOP enables the crea on of reusable components and applica ons with less
code, thus reducing development me and effort.
Maintainability: Since OOP encourages modularity, it’s easier to maintain, modify, and
debug programs. Addi onally, OOP helps keep code DRY (Don’t Repeat Yourself).
Key Concepts Explained:
1. Abstract Class and Abstrac on:
o Abstract classes and interfaces are used to implement abstrac on. They help in
hiding implementa on details and expose only the necessary features to the user.
o Example: An abstract Shape class defines a common method to calculate the area of
different shapes, while the derived classes (e.g., Circle, Rectangle) implement the
specific logic for each shape.
2. Polymorphism in Ac on:
o Polymorphism allows a method or object to take on different behaviors depending
on the context.
o Method Overriding: A base class can define a method (like MakeSound()), and the
derived classes (Dog, Cat) can override this method to provide their specific
implementa ons.
o Method Overloading: Methods can have the same name but different parameter
types or numbers, providing flexibility in how they are called.
3. Inheritance and Reusability:
o Inheritance enables code reuse by allowing a derived class to inherit proper es and
behaviors from a base class.
o Example: A Vehicle class can be extended by Car and Truck classes, each adding more
specific features like the number of doors or payload capacity while s ll inheri ng
common func onality like DisplayInfo().
4. Encapsula on for Security:
o Encapsula on ensures that an object's data is protected from direct access and
modifica on, allowing controlled interac on via methods (e.g., Deposit(),
Withdraw(), GetBalance()).
o Example: A BankAccount class encapsulates the balance field, and public methods
provide secure access to modify and retrieve the balance.
Conclusion:
Object-Oriented Programming provides a powerful paradigm for building well-structured and
maintainable so ware. By applying principles like abstrac on, encapsula on, inheritance, and
polymorphism, developers can create flexible, reusable, and secure applica ons.
Here’s a vivid documenta on style that brings the concepts to life with clear, concise explana ons,
and code examples:
C# Programming Language: A Comprehensive Guide
1. Introduc on to C#
What is C#? C# is a high-level, object-oriented programming language developed by Microso . It is a
part of the .NET ecosystem, widely used to build everything from desktop applica ons to mobile
apps, web services, and even games.
Why Learn C#?
Modern, powerful features like garbage collec on, LINQ, and async/await.
Seamless integra on with the Microso ecosystem (Windows, Azure, etc.).
Supports a wide range of development areas: apps, web, games, and more.
2. Basic Concepts in C#
Data Types:
Value Types: Includes int, float, double, char, bool, structs.
Reference Types: Includes string, arrays, classes, interfaces, and delegates.
int num = 10; // Value type
string name = "John"; // Reference type
Variables:
Declara on & Ini aliza on: Variables hold data and are declared with a type.
Type Inference: Use var to allow the compiler to infer the type.
int x = 5; // Explicit declara on
var y = 10; // Implicit declara on (compiler infers 'int')
Constants: Constants are immutable a er ini aliza on.
const double Pi = 3.14; // Pi is fixed
Enums: Enums make your code more readable by defining named constant values.
enum Day { Monday, Tuesday, Wednesday }
Day today = Day.Monday;
3. Control Flow
Condi onals: Use if-else to execute code based on condi ons.
if (x > 10)
Console.WriteLine("x is greater than 10");
else
Console.WriteLine("x is less than or equal to 10");
Switch Statement: A cleaner way to handle mul ple possible condi ons.
switch (day)
case "Monday":
Console.WriteLine("Start of the week");
break;
case "Friday":
Console.WriteLine("End of the week");
break;
default:
Console.WriteLine("Middle of the week");
break;
Loops:
For Loop: Loops through a specific range.
While Loop: Loops while a condi on is true.
Foreach Loop: Iterates through collec ons.
for (int i = 0; i < 5; i++)
Console.WriteLine(i); // Output: 0, 1, 2, 3, 4
int count = 0;
while (count < 5)
Console.WriteLine(count); // Output: 0, 1, 2, 3, 4
count++;
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
Console.WriteLine(number);
4. Object-Oriented Programming (OOP) in C#
Classes & Objects:
Class: A blueprint for objects.
Object: An instance of a class.
public class Car
public string Model;
public int Year;
public void Drive()
Console.WriteLine($"Driving a {Year} {Model}");
Car myCar = new Car();
myCar.Model = "Tesla";
myCar.Year = 2023;
myCar.Drive(); // Output: Driving a 2023 Tesla
Methods & Func ons: Methods are blocks of code that perform a specific task.
public int Add(int a, int b)
return a + b;
int result = Add(5, 3); // Output: 8
Constructors & Destructors:
Constructor: Ini alizes objects when created.
Destructor: Cleans up before the object is destroyed (handled by GC in C#).
public class Person
public string Name;
public Person(string name) // Constructor
Name = name;
}
Person p = new Person("John");
5. Inheritance, Polymorphism, Encapsula on, and Abstrac on
Inheritance: Allows a class to inherit proper es and methods from another class.
public class Animal
public void Eat() { Console.WriteLine("Ea ng..."); }
public class Dog : Animal
public void Bark() { Console.WriteLine("Barking..."); }
Dog dog = new Dog();
dog.Eat(); // Inherited method
dog.Bark(); // Dog's method
Polymorphism: Derived classes can modify base class methods.
public class Animal
public virtual void Speak()
Console.WriteLine("Animal Sound");
public class Dog : Animal
public override void Speak()
Console.WriteLine("Bark");
}
}
Animal myDog = new Dog();
myDog.Speak(); // Output: Bark
Encapsula on: Restricts access to certain class members and provides controlled access.
public class BankAccount
private double balance;
public void Deposit(double amount)
if (amount > 0) balance += amount;
public double GetBalance()
return balance;
Abstrac on: Hides implementa on details and exposes essen al features.
public abstract class Shape
public abstract double Area(); // Abstract method
public class Circle : Shape
public double Radius { get; set; }
public override double Area() => Math.PI * Radius * Radius;
6. Collec ons and Generics
Arrays: Fixed-size collec on.
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // Output: 1
Lists & Dic onaries: Dynamic collec ons, including key-value pairs.
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4);
Console.WriteLine(numbers[3]); // Output: 4
Dic onary<string, int> scores = new Dic onary<string, int>
{ "Alice", 85 },
{ "Bob", 90 }
};
Console.WriteLine(scores["Alice"]); // Output: 85
Generics: Defines type-safe collec ons or methods.
public class Box<T>
public T Item { get; set; }
Box<int> integerBox = new Box<int> { Item = 42 };
Console.WriteLine(integerBox.Item); // Output: 42
Crea ng Console Programs and C# Classes
Console Program: Introduc on and Crea on
A console program is a type of applica on that interacts with the user through a text-based interface,
typically using the command line or terminal. Unlike graphical user interface (GUI) applica ons,
console programs rely on text input and output.
Key Features of a Console Program:
1. Text-based interface: Interac on occurs through keyboard inputs and textual output.
2. Minimal system resources: Console programs are lightweight and typically do not consume
much memory or processing power.
3. Standard input/output: Input is received via the console, and output is printed to the
console.
Basic Console Program in C#
using System;
namespace ConsoleApp
class Program
sta c void Main(string[] args)
// Display a message
Console.WriteLine("Welcome to the Console Program!");
// Ask for user's name
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
// Ask for user's age
Console.Write("Please enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
// Calculate year of birth
int birthYear = DateTime.Now.Year - age;
// Output the result
Console.WriteLine($"Hello, {name}! You were born in {birthYear}.");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
Classes in C#
In C#, a class is a blueprint for crea ng objects (instances). It defines proper es (variables), methods
(func ons), and events that an object can have. Classes are fundamental to Object-Oriented
Programming (OOP).
Key Concepts of a Class:
1. Class Declara on:
public class Car
// Proper es, methods, constructors, etc. go here
2. Proper es: Variables that hold the data of an object, defining its state.
public class Car
public string Model { get; set; }
public string Color { get; set; }
public int Year { get; set; }
3. Methods: Func ons that define the behavior of an object.
public void DisplayDetails()
Console.WriteLine($"Model: {Model}, Color: {Color}, Year: {Year}");
4. Constructors: Special methods used to ini alize an object.
public Car(string model, string color, int year)
Model = model;
Color = color;
Year = year;
5. Access Modifiers: Control the visibility and accessibility of class members. Common
modifiers include:
o private: Accessible within the same class.
o public: Accessible from anywhere.
o protected: Accessible within the class and derived classes.
o internal: Accessible within the same assembly.
o protected internal: Accessible within the same assembly and derived classes.
Example of a Class in C#
using System;
namespace CarExample
public class Car
public string Model { get; set; }
public string Color { get; set; }
public int Year { get; set; }
public Car(string model, string color, int year)
Model = model;
Color = color;
Year = year;
public void DisplayDetails()
Console.WriteLine($"Model: {Model}, Color: {Color}, Year: {Year}");
class Program
sta c void Main(string[] args)
Car myCar = new Car("Tesla Model S", "Red", 2023);
myCar.DisplayDetails();
}
}
Types of Classes in C#
1. Sta c Class:
o A sta c class cannot be instan ated. It contains only sta c members.
o Typically used for u lity func ons.
public sta c class MathHelper
public sta c int Add(int a, int b)
return a + b;
2. Sealed Class:
o A sealed class cannot be inherited. It can s ll be instan ated.
public sealed class FinalClass
public void DisplayMessage()
Console.WriteLine("This is a sealed class.");
3. Abstract Class:
o An abstract class cannot be instan ated and may contain abstract methods, which
must be implemented in derived classes.
public abstract class Animal
public abstract void MakeSound();
public void Eat()
Console.WriteLine("Ea ng food.");
}
public class Dog : Animal
public override void MakeSound()
Console.WriteLine("Bark!");
4. Normal Class:
o A normal class can be instan ated, contains instance and sta c members, and can be
inherited unless sealed.
public class Vehicle
public string Make { get; set; }
public string Model { get; set; }
public void Drive()
Console.WriteLine("Driving the vehicle.");
5. Interface:
o An interface defines a contract that classes must implement.
public interface IDriveable
void Drive();
public class Car : IDriveable
{
public void Drive()
Console.WriteLine("Car is driving.");
Summary of Key Class Types:
Sta c Class: Cannot be instan ated. Contains only sta c members.
Sealed Class: Cannot be inherited.
Abstract Class: Cannot be instan ated directly. Used as a base class for other classes.
Normal Class: Can be instan ated, inherited, and contains both instance and sta c members.
Interface: Defines a contract for classes to implement.