Classes in C#
A class in C# is a basic idea in Object-Oriented Programming (OOP) and acts as a template or blueprint for object creation. It outlines the traits (data) and actions (functions) that belong to that kind of object. Classes in C# are intended to safely contain data and enable the insertion of related functions directly within the class description, in contrast to structures in C language or C++. At least one class must be present in any executable C# program.
Key Characteristics and Components of a Class
One fundamental OOP principle is encapsulation, which is how classes combine data and related functions into a single unit. This implies that data (attributes) can be concealed from direct external access and that class-defined methods govern how they are altered.
A class may have a number of members that specify its composition and capabilities:
Fields: These variables store an object’s information or state.
Methods: The actions or behaviours that an object is capable of performing are defined by these named code blocks. In C#, a method is the context in which all executable instructions operate.
Properties: These are unique members that offer a versatile method for reading, writing, or calculating private field values. They make data conveniently accessible while preserving the security and adaptability of get and set accessors.
Constructors: These are unique methods that are automatically called upon the creation of an object, which is an instance of the class. Initializing the new object’s class members is their main responsibility. Constructors lack a return type and are always named after the class.
Destructors: Just before an object is deleted from memory, the.NET runtime engine automatically invokes these methods, typically to release any allocated resources.
Indexers: These let you use an index to access things like an array.
Delegates: By defining a method’s signature, they allow methods to be regarded as parameters.
Events: These enable a notification pattern to be implemented.
Nested Classes: Classes that fall under another class’s definition.
Declaring a Class
The class keyword appears first in a class definition, followed by the class name. The body of the definition is encapsulated in two curly braces {}. To specify its visibility, an access modifier (such as public, private, protected, or internal) can come before the class keyword. The class name needs to be a case-sensitive, legitimate C# identifier. Everything in the class body is optional.
General Form of a Class Definition
[Access Modifier] class ClassName [: InheritedClass][, Interface1, Interface2, ...]
{
// Class members (fields, properties, methods, constructors, etc.)
}
Creating and Using Objects (Instances)
A concrete instance of a class is called an object. An object’s memory is only allotted during instantiation; the class is not declared at this time.
The new operator is used to create objects and to initialise the data members of the object by calling the relevant constructor. A variable of the class type to which an object is assigned after creation has a reference (memory address) to the object. To access members of an object (such fields, properties, and methods), apply the dot operator (.) to the variable of the object.
Code Examples
Class definition, member declaration, and object usage are demonstrated by the following examples:
A Basic “Hello World” Class: At the core of any C# executable program is the Main() method, which needs to be contained within a class.
using System; // Includes the System namespace
namespace HelloWorldApplication // Declares a namespace
{
class HelloWorld // Class declaration
{
static void Main(string[] args) // The Main method, entry point of the program
{
/* my first program in C# */ // Multi-line comment
Console.WriteLine("Hello World"); // Statement to print to console
System.Console.ReadKey(); // Waits for user input (common in console apps)
}
}
}
Output
Hello World
In this example:
class HelloWorld
declares a class with theHelloWorld
.static void Main(string[] args)
defines theMain
method, the program’s execution entry point.Console.WriteLine()
is a method call from theSystem.Console
class, demonstrating how to use a system class.
Class with Fields, Properties, and Methods (Example: Cat Class)
This example shows how a class can include data members (fields), properties for encapsulation, and methods and constructors for behaviour.
using System;
public class Cat // Class declaration with public access
{
// Fields - private instance variables to hold data
private string name;
private string color;
// Properties - public accessors for private fields
public string Name
{
get { return this.name; } // Getter for Name property
set { this.name = value; } // Setter for Name property
}
public string Color
{
get { return this.color; }
set { this.color = value; }
}
// Default Constructor - initializes object without parameters
public Cat()
{
this.name = "Unnamed";
this.color = "gray";
}
// Constructor with parameters - initializes object with provided values
public Cat(string name, string color)
{
this.name = name;
this.color = color;
}
// Method - defines the behavior of the object
public void SayMiau()
{
Console.WriteLine("Cat {0} said: Miauuuuuu!", name);
}
}
// Class to demonstrate usage of the Cat class
class CatManipulating
{
static void Main()
{
// Creating an object (instance) of the Cat class using the default constructor
Cat firstCat = new Cat();
firstCat.Name = "Tony"; // Accessing a property to set a value
firstCat.SayMiau(); // Calling a method on the object
// Creating another object using the parameterized constructor
Cat secondCat = new Cat("Pepy", "red");
secondCat.SayMiau();
Console.WriteLine("Cat {0} is {1}.", secondCat.Name, secondCat.Color); // Accessing properties to get values
}
}
Output
Cat Tony said: Miauuuuuu!
Cat Pepy said: Miauuuuuu!
Cat Pepy is red.