Skip to content

Classes and Objects

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.

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 state

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 Dog
alias.Name = "Rex";
Console.WriteLine(original.Name); // "Rex" -- original changed too! Same object, two variables
  1. What’s the difference between a class and an object?

    AnswerA class is the blueprint/definition; an object is a concrete instance created from that blueprint with new.
  2. If you assign one class-type variable to another (var b = a;), does that create a new object?

    AnswerNo β€” classes are reference types, so b now points to the same underlying object as a. Modifying through either variable affects the same object.
  3. Do two different instances of the same class share their field values?

    AnswerNo β€” each instance has its own independent copy of the class's instance fields; only the method implementations are shared.