C# Classes and Structs
Overview
Classes and structs are fundamental building blocks for defining custom data types in C#. They allow you to encapsulate data (fields) and behavior (methods) into a single unit.
Key Difference: Classes are reference types, meaning variables of a class type store a reference to an object in memory. Structs are value types, meaning variables of a struct type directly contain the struct's data.
Classes
A class defines a blueprint for creating objects. Objects are instances of a class. Classes support inheritance, polymorphism, and encapsulation.
public class Person
{
// Fields
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
To create an object (instance) of the Person class:
Person person1 = new Person("Alice", 30);
person1.Greet(); // Output: Hello, my name is Alice and I am 30 years old.
Structs
A struct is a value type that can have methods, fields, properties, and constructors. However, structs cannot contain default constructors (a constructor that takes no arguments) and cannot contain instance fields that are initialized in their declaration. They do not support inheritance (except implicitly from System.ValueType).
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
// Constructor (cannot be parameterless if fields are initialized)
public Point(int x, int y)
{
X = x;
Y = y;
}
public double DistanceFromOrigin()
{
return Math.Sqrt(X * X + Y * Y);
}
}
To create a struct instance:
Point p1 = new Point(10, 20);
Console.WriteLine($"Distance from origin: {p1.DistanceFromOrigin()}"); // Output: Distance from origin: 22.3606797749979
When to use structs: Consider using structs for small, lightweight data types that logically represent a single value and are often passed by value. Examples include coordinates, colors, or simple mathematical structures.
Key Concepts
- Fields: Variables declared within a class or struct to hold data.
- Methods: Functions defined within a class or struct to perform operations.
- Constructors: Special methods used to initialize objects when they are created.
- Properties: Accessors (
getandset) that provide controlled access to a class's or struct's fields. - Encapsulation: Bundling data and methods that operate on the data within a single unit (class or struct) and controlling access to that data.
- Value vs. Reference Types: Understanding the memory management and assignment behavior differences.