Learn C#: References
Unlock the power of references: an essential aspect of object-oriented programming in C#.
StartKey Concepts
Review core concepts you need to learn to master this subject
C# Reference Types
C# Object Reference
C# Object Reference Functionality
C# Polyphormism
C# Upcasting
C# Downcasting
C# Null Reference
C# Value Types
C# Reference Types
C# Reference Types
SportsCar sc = new SportsCar(100);
SportsCar sc2 = sc;
sc.SpeedUp(); // Method adds 20
Console.WriteLine(sc.Speed); // 120
Console.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#, 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.
An object of type Object
, string
, or dynamic
is also a reference type.
Reference Fundamentals
Lesson 1 of 3
- 1What do you think will be printed by this code? Dissertation diss1 = new Dissertation(); Dissertation diss2 = diss1; diss1.CurrentPage = 0; diss2.CurrentPage = 16; Console.WriteLine(diss1.CurrentP…
- 2Classes are reference types. That means that when we create a new instance of a class and store it in a variable, the variable is a reference to the object. Let’s see what’s happening behind t…
- 3To better grasp the idea of reference types, let’s look at the other kind of type: value types. While reference-type variables refer to a place in memory, value-type variables hold the actual dat…
- 4While reference-type variables refer to a place in memory, value-type variables hold the actual data. Let’s put that into practice with a little code.
- 5When we compare value types with ==, the C# compiler performs a value comparison. For example, this prints true because the value 6 is equal to the value 6: int int1 = 6; int int2 = 6; Console.Wr…
- 6Before going any further, let’s remind ourselves that Dissertation implements IFlippable, which has the CurrentPage property and Flip() method. You’ll need this info in a minute. In our previous …
- 7We know that we can use inherited classes and implemented interfaces to reference an object: Dissertation diss = new Dissertation(50); IFlippable fdiss = diss; This allows to work with many simila…
- 8We just saw how useful it is to have the same interface for multiple data types. This is a common concept across many programming languages, and it’s called polymorphism. The concept really inc…
- 10So far we’ve seen: * A reference to an object * Multiple references to an object What about a reference that refers to no object? In C# a reference to no object is called either a _null reference…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory