Object-Oriented Programming: Introduction to C# Syntax, Types, and Class-Based Object-Oriented Programming

 

1. Object-Oriented Programming: Introduction to C# Syntax, Types, and Class-Based Object-Oriented Programming

C# is an object-oriented programming (OOP) language, meaning it models real-world entities using classes and objects. Here’s a breakdown of some core concepts:

  • Classes: Templates for creating objects (instances).
  • Objects: Instances of classes.
  • Fields: Variables that hold the state of an object.
  • Methods: Functions that define behavior of an object.

Example:

public class Car { public string Make { get; set; } public string Model { get; set; } public void Drive() { Console.WriteLine("The car is driving."); } } class Program { static void Main() { Car car = new Car(); // Create an object of the Car class car.Make = "Toyota"; car.Model = "Corolla"; car.Drive(); // Call method on the object } }

2. Namespaces: Organizing Code Using Namespaces

Namespaces help organize code and avoid name conflicts. They are a way to group related classes, structs, interfaces, etc.

Example:

namespace Vehicles { public class Car { public string Make { get; set; } public string Model { get; set; } public void Drive() { Console.WriteLine("The car is driving."); } } } class Program { static void Main() { Vehicles.Car car = new Vehicles.Car(); // Using the namespace Vehicles car.Make = "Ford"; car.Model = "Fusion"; car.Drive(); } }

3. Basic Types: Primitive Types (int, float, string, etc.)

C# includes basic types that are used to store simple values like integers, floating-point numbers, characters, etc.

  • int: Whole numbers.
  • float: Floating-point numbers.
  • double: Larger floating-point numbers.
  • bool: Boolean values (true or false).
  • char: A single character.
  • string: A sequence of characters.

Example:

int age = 30; float height = 5.9f; double weight = 75.5; bool isStudent = true; char grade = 'A'; string name = "John";

4. Control Flow Statements: if, switch, for, foreach, while, and do-while

Control flow statements determine how the program executes based on conditions or iterations.

  • if: Conditional statement.
  • switch: Multi-way branch statement.
  • for: Loop for a known number of iterations.
  • foreach: Loop over collections.
  • while: Loop while a condition is true.
  • do-while: Similar to while, but checks the condition after executing the loop body.

Example:

class Program { static void Main() { int number = 10; // if statement if (number > 5) { Console.WriteLine("Number is greater than 5"); } // switch statement switch (number) { case 10: Console.WriteLine("Number is 10"); break; default: Console.WriteLine("Number is something else"); break; } // for loop for (int i = 0; i < 5; i++) { Console.WriteLine(i); } // foreach loop int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int num in numbers) { Console.WriteLine(num); } // while loop int counter = 0; while (counter < 3) { Console.WriteLine(counter); counter++; } // do-while loop int count = 0; do { Console.WriteLine(count); count++; } while (count < 3); } }

5. Exception Handling: try-catch-finally Blocks

Exception handling allows you to handle runtime errors gracefully. C# provides the try-catch-finally blocks for this purpose.

  • try: Contains code that might throw an exception.
  • catch: Handles exceptions.
  • finally: Always executes, whether an exception was thrown or not (usually for cleanup).

Example:

class Program { static void Main() { try { int result = 10 / 0; // This will throw an exception } catch (DivideByZeroException ex) { Console.WriteLine("Error: Division by zero is not allowed."); } finally { Console.WriteLine("Finally block executed."); } } }

6. Methods and Properties: Defining and Using Methods, Properties, and Constructors

  • Methods: Functions that belong to a class and define behaviors.
  • Properties: Encapsulate fields and allow controlled access.
  • Constructors: Special methods that are called when an object is instantiated.

Example:

public class Person { public string Name { get; set; } public int Age { get; set; } // Constructor public Person(string name, int age) { Name = name; Age = age; } // Method public void Introduce() { Console.WriteLine($"Hi, my name is {Name} and I am {Age} years old."); } } class Program { static void Main() { Person person = new Person("Alice", 25); // Constructor initializes fields person.Introduce(); // Call method } }

Access Levels

  • public: No restrictions, accessible from anywhere.
  • private: Accessible only within the class.
  • protected: Accessible within the class and derived classes.
  • internal: Accessible within the same assembly.

7. Events and Delegates: Defining and Subscribing to Events, and Using Delegates for Callback Methods

  • Delegates: A reference type that holds a reference to a method.
  • Events: Allow classes to notify other classes when something happens.

Example:

using System; // Delegate declaration public delegate void Notify(); // Class that publishes an event public class Publisher { // Event declaration public event Notify OnPublish; public void Publish() { Console.WriteLine("Publishing event..."); OnPublish?.Invoke(); // Invoke event if there are subscribers } } // Class that subscribes to the event public class Subscriber { public void OnEventPublished() { Console.WriteLine("Subscriber received the event."); } } class Program { static void Main() { Publisher publisher = new Publisher(); Subscriber subscriber = new Subscriber(); // Subscribe to the event publisher.OnPublish += subscriber.OnEventPublished; // Trigger the event publisher.Publish(); } }

8. Inheritance and Polymorphism: Fundamental OOP Concepts

  • Inheritance: Allows one class to inherit fields and methods from another class.
  • Polymorphism: Allows objects to be treated as instances of their parent class, even if they are instances of derived classes.

Example:

// Base class public class Animal { public virtual void Speak() { Console.WriteLine("The animal speaks."); } } // Derived class public class Dog : Animal { // Polymorphism: Override the Speak method public override void Speak() { Console.WriteLine("The dog barks."); } } class Program { static void Main() { Animal myAnimal = new Animal(); myAnimal.Speak(); // Output: The animal speaks. Dog myDog = new Dog(); myDog.Speak(); // Output: The dog barks. Animal polymorphicDog = new Dog(); polymorphicDog.Speak(); // Output: The dog barks. (Polymorphism) } }

Conclusion

These are fundamental concepts of C# and object-oriented programming in .NET. We covered:

  1. Basic object-oriented concepts and syntax in C#.
  2. Organizing code with namespaces.
  3. Usage of basic types.
  4. Control flow statements like if, for, while, etc.
  5. Exception handling with try-catch-finally.
  6. Defining and using methods, properties, and constructors.
  7. Working with events and delegates.
  8. Implementing inheritance and polymorphism.

Post a Comment