Classes and Objects
Classes and Objects
Section titled βClasses and ObjectsβWhat it means
Section titled βWhat it meansβA class is a blueprint that defines the fields (data) and methods (behavior) something should have. An object (or instance) is a concrete thing created from that blueprint with new. Each object has its own independent copy of the classβs instance fields, but they all share the same method implementations.
Examples
Section titled βExamplesβpublic class Dog{ public string Name; public string Breed;
public string Bark() => $"{Name} says Woof!";}
var fido = new Dog { Name = "Fido", Breed = "Labrador" };var rex = new Dog { Name = "Rex", Breed = "Poodle" };
Console.WriteLine(fido.Bark()); // "Fido says Woof!"Console.WriteLine(rex.Bark()); // "Rex says Woof!" -- same method, different data
Console.WriteLine(fido.Name == rex.Name); // False -- separate instances, separate stateCommon mistake
Section titled βCommon mistakeβConfusing a class (reference type) with a struct (value type) when it comes to copying β assigning one class instance to another variable copies the reference, not the object, so changes through either variable affect the same underlying object.
public class Dog { public string Name; }
var original = new Dog { Name = "Fido" };var alias = original; // copies the REFERENCE, not a new Dogalias.Name = "Rex";
Console.WriteLine(original.Name); // "Rex" -- original changed too! Same object, two variablesQuick practice
Section titled βQuick practiceβ-
Whatβs the difference between a class and an object?
Answer
A class is the blueprint/definition; an object is a concrete instance created from that blueprint withnew. -
If you assign one class-type variable to another (
var b = a;), does that create a new object?Answer
No β classes are reference types, sobnow points to the same underlying object asa. Modifying through either variable affects the same object. -
Do two different instances of the same class share their field values?
Answer
No β each instance has its own independent copy of the class's instance fields; only the method implementations are shared.