0% found this document useful (0 votes)
21 views13 pages

Learn C# - Learn C# - References Cheatsheet - Codecademy

The document is a cheatsheet for learning C# that covers key concepts such as reference types, object references, polymorphism, upcasting, downcasting, null references, value types, and string handling. It provides code examples to illustrate how these concepts work in practice, including comparisons between value and reference types, and the behavior of strings in C#. Additionally, it explains the Object class and its methods, emphasizing the importance of understanding these foundational elements in C# programming.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views13 pages

Learn C# - Learn C# - References Cheatsheet - Codecademy

The document is a cheatsheet for learning C# that covers key concepts such as reference types, object references, polymorphism, upcasting, downcasting, null references, value types, and string handling. It provides code examples to illustrate how these concepts work in practice, including comparisons between value and reference types, and the behavior of strings in C#. Additionally, it explains the Object class and its methods, emphasizing the importance of understanding these foundational elements in C# programming.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

Cheatsheets / Learn C#

Learn C#: References

C# Reference Types

In C#, classes and interfaces are reference types. SportsCar sc = new SportsCar(100);
Variables of reference types store references to their
SportsCar sc2 = sc;
data (objects) in memory, and they do not contain the
data itself. sc.SpeedUp(); // Method adds 20
An object of type Object , string , or dynamic is Console.WriteLine(sc.Speed); // 120
also a reference type.
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.

C# Object Reference

In C#, an object may be referenced by any type in its // Woman inherits from Human, which
inheritance hierarchy or by any of the interfaces it
inherits from Animal, and it implements
implements.
IPerson:
class Human : Animal
class Woman : Human, IPerson

// All of these references are valid:


Woman eve = new Woman();
Human h = eve;
Animal a = eve;
IPerson p = eve;

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 1/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Object Reference Functionality

In C#, the functionality available to an object reference Player p = new Player();


is determined by the reference’s type, not the object’s
Fan f = p;
type.
p.SignContract();
f.SignContract();
// Error! 'SignContract()` is not defined
for the type 'Fan'

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 2/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Polymorphism

Polymorphism is the ability in programming to present class Novel : Book


the same interface for different underlying forms (data
{
types).
We can break the idea into two related concepts. A public override string Stringify()
programming language supports polymorphism if: {
1. Objects of different types have a common
return "This is a Novel!;
interface (interface in the general meaning, not
just a C# interface), and }
2. The objects can maintain functionality unique to }
their data type

class Book
{
public virtual string Stringify()
{
return "This is a Book!;
}
}

// In the below code, you’ll see that a


Novel and Book object can both be
referred to as Books. This is one of
their shared interfaces. At the same
time, they are different data types with
unique functionality.

Book bk = new Book();


Book warAndPeace = new Novel();
Console.WriteLine(bk.Stringify());
Console.WriteLine(warAndPeace.Stringify()
);

// This is a Book!
// This is a Novel

// Even though bk and warAndPeace are the


same type of reference, their behavior is
different. Novel overrides the
Stringify() method, so all Novel objects
(regardless of reference type) will use
that method.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 3/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Upcasting

In C#, upcasting is creating an inherited superclass or // In this case, string inherits from
implemented interface reference from a subclass
Object:
reference.

string s = "Hi";
Object o = s;

// In this case, Laptop implements the


IPortable interface:

Laptop lap = new Laptop();


IPortable portable = lap;

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 4/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Downcasting

In C#, downcasting is creating a subclass reference // Dog inherits from Pet. An implicit
from a superclass or interface reference.
downcast throws a compile-time error:
Downcasting can lead to runtime errors if the
superclass cannot be cast to the specified subclass. Pet pet = new Pet();
Dog dog = pet;
Account a = new Account();
// error CS0266: Cannot implicitly
CustomerAccount ca = a;
convert type `Pet` to `Dog`. An explicit
// error CS0266: Cannot implicitl
conversion exists (are you missing a
cast?)

// Every downcast must be explicit, using


the cast operator, like (TYPE). This
fixes the compile-time error but raises a
new runtime error.
Pet pet = new Pet();
Dog dog = (Pet)pet;
// runtime error:
System.InvalidCastException: Specified
cast is not valid.

//The explicit downcast would only work


if the underlying object is of type Dog:
Dog dog = new Dog();
Pet pet = dog;
Dog puppy = (Dog)pet;

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 5/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Null Reference

In C#, an undefined reference is either a null reference MyClass mc; //unassigned


or unassigned. A null reference is represented by the
keyword null .
Be careful when checking for null and unassigned Console.WriteLine (mc == null);
references. We can only compare a null reference if it is // error CS0165: Use of unassigned local
explicitly labeled null .
variable 'mc'

MyClass mc = null; //explicitly 'null'

Console.WriteLine(mc == null);
// Prints true.

// Array of unassigned references


MyClass[] objects = new MyClass[5];
// objects[0] is unassigned, objects[1]
is unassigned, etc...

C# Value Types

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 , DateTime
All numeric data types
Structures ( struct )
Enumerations ( enum )

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 6/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Comparison Type

In C#, the type of comparison performed with the // int is a value type, so == uses value
equality operator ( == ), differs with reference and
equality:
value types.
When two value types are compared, they are int num1 = 9;
compared for value equality. They are equal if they int num2 = 9;
hold the same value.
Console.WriteLine(num1 == num2);
When two reference types are compared, they are
compared for referential equality. They are equal if // Prints true
they refer to the same location in memory.

// 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):

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 7/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Override

In C#, the override modifier allows base class // In the below example,
references to a derived object to access derived
DerivedClass.Method1() overrides
methods.
In other words: If a derived class overrides a member of BaseClass.Method1(). bcdc is a BaseClass-
its base class, then the overridden version can be type reference to a DerivedClass value.
accessed by derived references AND base references.
Calling bcdc.Method1() invokes
DerivedClass.Method1().

class MainClass {
public static void Main (string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();

bc.Method1();
dc.Method1();
bcdc.Method1();
}
}

class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base -
Method1");
}
}

class DerivedClass : BaseClass


{
public override void Method1()
{
Console.WriteLine("Derived -
Method1");
}
}

// The above code produces this result:

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 8/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy
// Base - Method1
// Derived - Method1
// Derived - Method1

// If we wanted bcdc.Method1() to invoked


BaseClass.Method1(), then we would label
DerivedClass.Method1() as new, not
override.

C# String Comparison

In C#, string is a reference type but it can be //In this example, even if s and t are
compared by value using == .
not referentially equal, they are equal
by value:
string s = "hello";
string t = "hello";

// b is true
bool b = (s == t);

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 9/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# String Types Immutable

In C#, string types are immutable, which means they // Two examples demonstrating how
cannot be changed after they are created.
immutablility determines string behavior.
In both examples, changing one string
variable will not affect other variables
that originally shared that value.

//EXAMPLE 1
string a = "Hello?";
string b = a;
b = "HELLLLLLLO!!!!";

Console.WriteLine(b);
// Prints "HELLLLLLLO!!!!"

Console.WriteLine(a);
// Prints "Hello?"

//EXAMPLE 2
string s1 = "Hello ";
string s2 = s1;
s1 += "World";

System.Console.WriteLine(s2);
// Prints "Hello "

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 10/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Empty String

In C#, a string reference can refer to an empty string // Empty string:


with "" and String.Empty .
string s1 = "";
This is separate from null and unassigned references,
which are also possible for string types.
// Also empty string:
string s2 = String.Empty;

// This prints true:


Console.WriteLine(s1 == s2);

// Unassigned:
string s3;

// Null:
string s4 = null;

C# Object Class

In C#, the base class of all types is the Object class. // When you write this code:
Every class implicitly inherits this class.
class Dog {}
When you create a class with no inheritance, C#
implicitly makes it inherit from Object . // C# assumes you mean:
class Dog : Object {}

//Even if your class explicitly inherits


from a class that is NOT an Object, then
some class in its class hierachy will
inherit from Object. In the below
example, Dog inherits from Pet, which
inherits from Animal, which inherits from
Object:
class Dog : Pet {}
class Pet : Animal {}
class Animal {}

//Since every class inherits from Object,


any instance of a class can be referred
to as an Object.
Dog puppy = new Dog();
Object o = puppy;

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 11/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# Object Class Methods

In C#, the Object class includes definitions for these Object obj = new Object();
methods: ToString() , Equals(Object) , and
Console.WriteLine(obj.ToString());
GetType() .
// The example displays the following
output:
// System.Object

public static void Main()


{
MyBaseClass myBase = new
MyBaseClass();
MyDerivedClass myDerived = new
MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;

Console.WriteLine("mybase: Type
is {0}", myBase.GetType());
Console.WriteLine("myDerived: Type is
{0}", myDerived.GetType());
Console.WriteLine("object o =
myDerived: Type is {0}", o.GetType());
Console.WriteLine("MyBaseClass b =
myDerived: Type is {0}", b.GetType());
}

// The example displays the following


output:
// mybase: Type is MyBaseClass
// myDerived: Type is MyDerivedClass
// object o = myDerived: Type is
MyDerivedClass
// MyBaseClass b = myDerived: Type is
MyDerivedClass

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 12/13
10-02-2024 16:04 Learn C#: Learn C#: References Cheatsheet | Codecademy

C# ToString() Method

When a non-string object is printed to the console with Random r = new Random();
Console.WriteLine() , its ToString() method is
called.
// These two lines are equivalent:
Console.WriteLine(r);
Console.WriteLine(r.ToString());

Print Share

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-references/cheatsheet 13/13

You might also like