Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 2 : Advanced C# Programming

This is the heart of professional C# development. Moving from “code that runs” to Object-Oriented Programming (OOP) is what separates a scripter from a Software Engineer. In the enterprise world, code is read 10x more than it is written, and these concepts are designed to make code maintainable.

1. Classes & Objects

Think of a Class as a blueprint or a template. It defines what data an entity should have and what it can do. An Object is the actual house built from that blueprint.

  • Class: Car (The concept of a car).
  • Object: myTesla, myFord (Specific instances of a car).

The “Anatomy”

  • Fields: Variables inside a class (e.g., string color;).
  • Properties: A way to safely access those fields (using get and set).
  • Methods: The actions the class can take (e.g., Drive(), Brake()).

2. Constructors & Destructors

These are “Special Methods” that handle the lifecycle of an object.

  • Constructor: A method that runs automatically the moment you create an object (new Car()). It is used to initialize data.
    • Enterprise Tip: We often use Dependency Injection here to pass services into our classes.
  • Destructor (Finalizer): A method that runs when the object is destroyed. In C#, we rarely use these because the Garbage Collector manages memory for us. However, they are used for closing file streams or database connections.

3. Inheritance & Polymorphism

These two allow you to reuse code and create flexible systems.

  • Inheritance: Creating a “Parent-Child” relationship. A Truck class can inherit from a Vehicle class, gaining its properties like Speed and Fuel without rewriting them.
  • Polymorphism: (Greek for “Many Shapes”). It allows a child class to change how a parent’s method works.
    • Method Overriding: A Dog and Cat both inherit MakeSound() from Animal, but one says “Woof” and the other “Meow.”

4. Interfaces vs. Abstract Classes

This is a classic senior-level interview question.

FeatureInterfaceAbstract Class
PurposeA “Contract” of what to do.A “Base” for what something is.
ImplementationContains NO logic (only signatures).Can contain logic and shared code.
Multiple?A class can implement many interfaces.A class can inherit only one class.
  • Abstract Class: Use when you want to provide a common base for closely related objects (e.g., Shape as a base for Circle and Square).
  • Interface: Use when you want to define a behavior that many unrelated classes might share (e.g., ILoggable could be used by a User class AND a Database class).

5. Access Modifiers

These control “Visibility.” They are the “security guards” of your code.

  1. public: Anyone can see it.
  2. private: Only code inside the same class can see it. (This is the default).
  3. protected: The class itself and its “children” (via inheritance) can see it.
  4. internal: Only code inside the same project (Assembly) can see it.

6. Encapsulation & SOLID Principles

Encapsulation

The practice of hiding the internal state of an object and requiring all interaction to happen through public methods. This prevents other developers from “breaking” your object by setting an Age to -500.

SOLID Principles

These are the five commandments of clean code.

  • S – Single Responsibility: A class should have only ONE reason to change (one job).
  • O – Open/Closed: Your code should be open for extension but closed for modification.
  • L – Liskov Substitution: You should be able to replace a parent class with a child class without the program breaking.
  • I – Interface Segregation: Don’t force a class to implement methods it doesn’t need. Split big interfaces into small ones.
  • D – Dependency Inversion: Depend on abstractions (Interfaces), not on concrete “hard-coded” classes.

Advanced Concept

To master these “Advanced Concepts,” you must move away from thinking about data and start thinking about behavior. In C#, these topics allow you to treat methods like variables—passing logic around your application as easily as you would pass an integer.

1. Delegates

A Delegate is technically a “Type-safe Function Pointer.” In simpler terms, it is a variable that holds a reference to a method instead of a value.

  • The Analogy: If a variable is a “Box” for data, a Delegate is a “Plug” for a method. You can swap the “machine” (method) plugged into it at any time.
  • Why use them? They allow your code to be flexible. Instead of hard-coding what happens after a task finishes, you let the caller “plug in” their own method.

The Three Built-in Delegates (The Enterprise Standard)

Instead of creating custom delegates, modern .NET developers almost always use these:

  1. Action: For methods that return void (do something, return nothing).
  2. Func: For methods that return a value (calculate something, return the result).
  3. Predicate: A special version of Func that always returns a bool (used for filtering).

2. Events

Events are built on top of delegates. They follow the Publisher-Subscriber Pattern.

  • The Publisher: The class that sends the notification (e.g., a “Download” button or a “Stock Price Tracker”).
  • The Subscriber: The class that wants to know when the event happens (e.g., a “Logging” service or a “UI Progress Bar”).

The Key Difference: While a delegate can be called by anyone who has access to it, an Event can only be “fired” (triggered) from within the class that defined it. This provides a layer of security and encapsulation.


3. Anonymous Methods

Before C# had modern syntax, if you wanted to pass logic to a delegate, you had to write a whole separate method. Anonymous Methods allowed developers to write “inline” code without giving the method a name.

C#

// The old way: writing a separate method
button.Click += delegate(object sender, EventArgs e) {
    Console.WriteLine("Button was clicked!");
};

Note: These are rarely used today because Lambda Expressions (explained below) are much cleaner.


4. Lambda Expressions

A Lambda Expression is the evolution of the anonymous method. It is a short, highly readable way to write a method locally.

  • The Syntax: (input parameters) => expression/statement
  • The “Fat Arrow” (=>): Read this as “goes to.”

Example Comparison:

  • Standard Method: int Square(int x) { return x * x; }
  • Lambda Version: x => x * x;

Lambdas are the “secret sauce” behind LINQ (Language Integrated Query), which is how enterprise developers filter through thousands of database records with a single line of code.


Outcome: Thinking in OOP Design Patterns

By combining these concepts, you stop writing “Spaghetti Code” and start using Design Patterns.

Common Patterns You Can Now Understand:

  1. Strategy Pattern: Using delegates/interfaces to swap algorithms at runtime (e.g., switching from “Credit Card Payment” logic to “PayPal” logic).
  2. Observer Pattern: Using Events to notify multiple parts of an app when one thing changes (e.g., updating a dashboard when a new sale occurs).
  3. Dependency Injection: Passing behavior (as interfaces or delegates) into a class so the class doesn’t have to worry about the “how,” only the “what.”

A Concrete Example

Imagine a NotificationService. Instead of it knowing how to send Emails, SMS, and Push notifications (which violates the Single Responsibility Principle), it just has an Event: OnMessageReceived.

Other specialized classes (EmailService, SMSService) “subscribe” to that event. This makes your code Open/Closed: Open for new notification types, but Closed for modification of the core service.

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥