Classes and Objects
In C#, a class is a blueprint for creating objects. It defines the properties (data members) and behaviors (methods) that objects of that class will have. An object is an instance of a class, representing a concrete entity based on the class's definition.
Defining a Class
You define a class using the class
keyword, followed by the class name. Inside the class definition, you declare fields (variables) and methods.
public class Car
{
// Fields (Data Members)
public string make;
public string model;
public int year;
// Methods (Behaviors)
public void StartEngine()
{
Console.WriteLine("Engine started!");
}
public void DisplayInfo()
{
Console.WriteLine($"Car: {year} {make} {model}");
}
}
Explanation:
public class Car
: Declares a class namedCar
. Thepublic
access modifier means this class can be accessed from any other code.public string make;
: Declares a public field namedmake
of typestring
.public void StartEngine()
: Declares a public method namedStartEngine
that doesn't return any value (void
).
Creating Objects (Instances)
To create an object from a class, you use the new
keyword followed by the class name and parentheses. This process is called instantiation.
// Create an instance of the Car class
Car myCar = new Car();
// Set the properties of the object
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2023;
// Call methods on the object
myCar.StartEngine();
myCar.DisplayInfo();
Output:
Engine started!
Car: 2023 Toyota Camry
Constructors
A constructor is a special method within a class that is automatically called when an object of that class is created. It's used to initialize the object's fields.
If you don't define a constructor, C# provides a default parameterless constructor.
public class Person
{
public string name;
public int age;
// Constructor
public Person(string personName, int personAge)
{
name = personName;
age = personAge;
Console.WriteLine($"A new person named {name} was created.");
}
public void Greet()
{
Console.WriteLine($"Hello, my name is {name} and I am {age} years old.");
}
}
// Creating an object using the constructor
Person person1 = new Person("Alice", 30);
person1.Greet();
Output:
A new person named Alice was created.
Hello, my name is Alice and I am 30 years old.
Properties
While fields can be directly accessed and modified, it's generally better practice to use properties. Properties provide a flexible mechanism to read, write, or compute the value of a private field.
public class Product
{
private string _name; // Private backing field
private decimal _price;
// Public property for Name
public string Name
{
get { return _name; } // Getter
set { _name = value; } // Setter
}
// Public property for Price with validation
public decimal Price
{
get { return _price; }
set
{
if (value >= 0) // Ensure price is not negative
{
_price = value;
}
else
{
Console.WriteLine("Price cannot be negative.");
}
}
}
public void DisplayProductDetails()
{
Console.WriteLine($"Product: {Name}, Price: ${Price}");
}
}
// Using properties
Product laptop = new Product();
laptop.Name = "SuperBook Pro";
laptop.Price = 1200.50m; // 'm' denotes a decimal literal
laptop.DisplayProductDetails();
// Attempting to set an invalid price
laptop.Price = -50.00m;
Output:
Product: SuperBook Pro, Price: $1200.50
Price cannot be negative.
Access Modifiers
Access modifiers control the visibility and accessibility of classes, fields, methods, and other members.
Modifier | Description |
---|---|
public |
Accessible from anywhere. |
private |
Accessible only within the defining class. (Default for members) |
protected |
Accessible within the defining class and by derived classes. |
internal |
Accessible within the same assembly (project). |
protected internal |
Accessible within the same assembly or by derived classes in other assemblies. |
private protected |
Accessible within the same assembly and by derived classes within that assembly. |
- Classes are blueprints for objects.
- Objects are instances of classes.
- Constructors initialize objects when they are created.
- Properties provide controlled access to object data.
- Access modifiers define the visibility of class members.