C# - Classes
In C#, classes are fundamental building blocks of object-oriented programming. A class is a blueprint for creating objects (instances), encapsulating data and methods that operate on the data. Here’s a comprehensive guide to understanding and using classes in C#:
1. Defining a Class
A class in C# is defined using the class
keyword, followed by the class name and its body enclosed in curly braces.
Syntax:
csharppublic class ClassName
{
// Fields
// Properties
// Methods
// Constructors
}
Example:
csharppublic class Person
{
// Fields
public string Name;
public int Age;
// Method
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
2. Creating an Instance
To create an instance of a class, use the new
keyword followed by the class name and parentheses.
Example:
csharpPerson person = new Person();
person.Name = "Alice";
person.Age = 30;
person.Introduce(); // Outputs: Hello, my name is Alice and I am 30 years old.
3. Constructors
Constructors are special methods that are called when an object is instantiated. They are used to initialize the object’s state.
Syntax:
csharppublic ClassName()
{
// Initialization code
}
Example:
csharppublic class Person
{
public string Name;
public int Age;
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
// Creating an instance using the constructor
Person person = new Person("Bob", 25);
person.Introduce(); // Outputs: Hello, my name is Bob and I am 25 years old.
4. Properties
Properties provide a way to access and modify the private fields of a class. They include get
and set
accessors.
Syntax:
csharppublic class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
Example:
csharppublic class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name}.");
}
}
Person person = new Person();
person.Name = "Charlie";
person.Introduce(); // Outputs: Hello, my name is Charlie.
5. Methods
Methods define the behavior of the class. They can perform operations using the class's fields and properties.
Example:
csharppublic class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
6. Fields
Fields are variables declared directly within a class. They represent the state of an object.
Example:
csharppublic class Car
{
public string Make;
public string Model;
public int Year;
}
7. Inheritance
Inheritance allows a class to inherit fields, properties, and methods from another class. The derived class (child) inherits from the base class (parent).
Syntax:
csharppublic class BaseClass
{
// Base class members
}
public class DerivedClass : BaseClass
{
// Derived class members
}
Example:
csharppublic class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
Dog dog = new Dog();
dog.Eat(); // Inherited method
dog.Bark(); // Derived class method
8. Abstract Classes
An abstract class cannot be instantiated directly and is meant to be a base class for other classes. It can contain abstract methods that derived classes must implement.
Syntax:
csharppublic abstract class AbstractClass
{
public abstract void AbstractMethod();
public void ConcreteMethod()
{
Console.WriteLine("This is a concrete method.");
}
}
Example:
csharppublic abstract class Shape
{
public abstract double GetArea();
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double GetArea()
{
return Width * Height;
}
}
Rectangle rect = new Rectangle { Width = 5, Height = 10 };
Console.WriteLine(rect.GetArea()); // Outputs: 50
9. Interfaces
An interface defines a contract that classes can implement. It cannot contain implementation, only method signatures and properties.
Syntax:
csharppublic interface IInterface
{
void Method();
}
Example:
csharppublic interface IShape
{
double GetArea();
}
public class Circle : IShape
{
public double Radius { get; set; }
public double GetArea()
{
return Math.PI * Radius * Radius;
}
}
Circle circle = new Circle { Radius = 3 };
Console.WriteLine(circle.GetArea()); // Outputs: 28.274333882308138
10. Encapsulation
Encapsulation is the principle of bundling data (fields) and methods that operate on the data into a single unit (class) and restricting access to some of the object’s components. It is achieved through access modifiers.
11. Static Classes and Members
Static classes cannot be instantiated and can only contain static members. Static members belong to the class itself rather than to any instance.
Syntax:
csharppublic static class Utility
{
public static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
Example:
csharpUtility.PrintMessage("Hello, World!"); // Outputs: Hello, World!
Summary
Classes in C# are essential for creating object-oriented applications. They encapsulate data and behavior, support inheritance, and can be used to model real-world entities. Understanding how to define and use classes, including concepts like constructors, properties, methods, fields, inheritance, and interfaces, will help you build robust and maintainable applications. By leveraging encapsulation, abstraction, and static members, you can design flexible and efficient code structures.