-
Notifications
You must be signed in to change notification settings - Fork 5
Classes and Objects
A class is a blueprint for creating objects, providing properties and methods to define behavior. An object is an instance of a class, encapsulating data and functionality.
A class is a user-defined reference type that acts as a blueprint for objects.
Syntax:
class ClassName {
// Fields
// Properties
// Methods
// Constructors
}
class Car {
public string Brand; // Field
public void Drive() { // Method
Console.WriteLine($"{Brand} is driving.");
}
}
An object is an instance of a class that holds data and can invoke methods.
Syntax:
ClassName obj = new ClassName();
Car myCar = new Car();
myCar.Brand = "Toyota"; // Accessing field
myCar.Drive(); // Output: Toyota is driving.
Variables declared within a class to hold data.
Example:
class Person {
public string Name;
public int Age;
}
Encapsulate fields with
get
andset
for controlled access.
Example:
class Person {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
}
Functions inside a class that define behavior.
Example:
class Calculator {
public int Add(int a, int b) {
return a + b;
}
}
Special methods to initialize objects.
Example:
class Car {
public string Brand;
public Car(string brand) { // Constructor
Brand = brand;
}
}
Car myCar = new Car("Ford"); // Constructor invoked
Control access to class members.
Modifier | Description | Example |
---|---|---|
public |
Accessible from anywhere. | public int Age; |
private |
Accessible only within the same class. | private int age; |
protected |
Accessible within the same class and derived classes. | protected int age; |
internal |
Accessible within the same assembly. | internal int age; |
class Dog {
// Fields
private string breed;
// Property
public string Breed {
get { return breed; }
set { breed = value; }
}
// Constructor
public Dog(string breed) {
Breed = breed;
}
// Method
public void Bark() {
Console.WriteLine($"{Breed} is barking.");
}
}
// Object creation
Dog myDog = new Dog("Golden Retriever");
myDog.Bark(); // Output: Golden Retriever is barking.
- Class: Blueprint for creating objects, containing fields, properties, methods, and constructors.
- Object: Instance of a class, encapsulating state and behavior.
- Components: Include fields (data), properties (controlled access), methods (behavior), and constructors (initialization).
- Access Modifiers: Control visibility and accessibility of members.
Classes and objects form the foundation of Object-Oriented Programming in C#, promoting modularity, reusability, and encapsulation.
Using properties instead of directly exposing fields in C# is a good practice due to the benefits of encapsulation, data validation, and flexibility. While fields are simple and straightforward, they lack the ability to control how data is accessed or modified.
- Fields: Directly exposing fields makes it impossible to control how data is accessed or modified.
-
Properties: With
get
andset
, you can control the logic for accessing or modifying a value.
Example:
class Person {
public string Name; // Direct field (no control)
}
Versus:
class Person {
private string name;
public string Name {
get { return name; }
set {
if (!string.IsNullOrEmpty(value)) { // Validation
name = value;
} else {
throw new ArgumentException("Name cannot be empty.");
}
}
}
}
- Fields: No way to validate data before setting it.
- Properties: You can add logic to ensure data consistency.
Example:
class Employee {
private int age;
public int Age {
get { return age; }
set {
if (value > 0) {
age = value; // Only set valid ages
} else {
throw new ArgumentException("Age must be positive.");
}
}
}
}
- Fields: Cannot restrict access for reading or writing.
-
Properties: Can make a property read-only (
get
only) or write-only (set
only).
Example:
class Product {
private int stock;
public int Stock {
get { return stock; } // Read-only
}
public void Restock(int amount) { // Write logic encapsulated in a method
if (amount > 0) {
stock += amount;
}
}
}
- Simplify property declarations while still maintaining encapsulation.
Example:
class Book {
public string Title { get; set; } // Auto-implemented property
public string Author { get; set; }
}
This avoids the verbosity of manually implementing backing fields unless you need custom logic.
- Fields: Once exposed, you cannot later add logic to control access without breaking the API.
- Properties: Let you modify the internal logic (e.g., add validation, logging, or computed values) without changing the external interface.
Example:
class Rectangle {
private int length;
public int Length {
get { return length; }
set {
if (value > 0) length = value;
}
}
// Adding a computed property later
public int Area {
get { return length * length; } // Derived value
}
}
- Fields are suitable for private members that are not meant to be accessed directly outside the class.
- Use fields for constants (
const
) or read-only values (readonly
) where properties would add unnecessary overhead.
Example:
class Circle {
private const double Pi = 3.14159; // Constant field
private readonly double radius; // Read-only field
public Circle(double radius) {
this.radius = radius;
}
}
Feature | Field | Property |
---|---|---|
Encapsulation | No control over access/modification. | Allows full control via get and set . |
Data Validation | Not possible. | Can validate data before setting it. |
Access Control | Always read-write. | Can be read-only or write-only. |
Flexibility | No room for future changes. | Logic can evolve without breaking the interface. |
Use Case | Internal/private constants. | Exposed data requiring control or validation. |
In summary, use properties when exposing data to maintain control and flexibility. Fields are best kept private or used for fixed, internal values.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.