In C#, classes and interfaces are reference types. Variables of reference types store references to their data (objects) in memory, and they do not contain the data itself.
SportsCar sc = new SportsCar(100);SportsCar sc2 = sc;sc.SpeedUp(); // Method adds 20Console.WriteLine(sc.Speed); // 120Console.WriteLine(sc2.Speed); // 120// In this code, sc and sc2 refer to the same object. The last two lines will print the same value to the console.
In C#, an object may be referenced by any type in its inheritance hierarchy or by any of the interfaces it implements.
// Crow inherits from Bird, which inherits from Animal, and it implements IFly:class Bird : Animal{ }class Crow : Bird, IFly{ }// All of these references are valid:Crow crow = new Crow();Bird b = crow;Animal a = crow;IFly f = crow;
In C#, the functionality available to an object reference is determined by the reference’s type, not the object’s type.
Cat c = new Cat();Animal a = c;c.Meow(); // OK, 'Meow()' is defined for the type 'Cat'a.Meow();// Error! 'Meow()' is not defined for the type 'Animal'
In C#, value types contain the data itself. They include int
, bool
, char
, and double
.
Here’s the entire list of value types:
char
, bool
struct
)enum
)In C#, the type of comparison performed with the equality operator (==
) differs between reference and value types.
When two value types are compared, they are compared for value equality. They are equal if they hold the same value.
When two reference types are compared, they are compared for referential equality. They are equal if they refer to the same location in memory.
// int is a value type, so == uses value equality:int num1 = 9;int num2 = 9;Console.WriteLine(num1 == num2);// Prints true// All classes are reference types, so == uses reference equality:WorldCupTeam japan = new WorldCupTeam(2018);WorldCupTeam brazil = new WorldCupTeam(2018);Console.WriteLine(japan == brazil);// Prints false// This is because japan and brazil refer to two different locations in memory (even though they contain objects with the same values):