Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Learn C#_ Learn C#_ Classes and Objects Cheatsheet _ Codecademy

This document is a cheatsheet for learning C# classes and objects, covering key concepts such as class definitions, constructors, access modifiers, fields, properties, and the use of the 'this' keyword. It explains how to create and use classes, including parameterless constructors and static classes, as well as the role of members and dot notation in accessing class data. The document serves as a concise reference for understanding the foundational elements of object-oriented programming in C#.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Learn C#_ Learn C#_ Classes and Objects Cheatsheet _ Codecademy

This document is a cheatsheet for learning C# classes and objects, covering key concepts such as class definitions, constructors, access modifiers, fields, properties, and the use of the 'this' keyword. It explains how to create and use classes, including parameterless constructors and static classes, as well as the role of members and dot notation in accessing class data. The document serves as a concise reference for understanding the foundational elements of object-oriented programming in C#.

Uploaded by

Michael Okocha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

Cheatsheets / Learn C#

Learn C#: Classes and Objects

C# Classes

In C#, classes are used to create custom types. The using System;
class defines the kinds of information and methods
included in a custom type.
namespace BasicClasses
{
class Forest {
public string name;
public int trees;
}
}

// Here we have the Forest class which


has two pieces of data, called fields.
They are the "name" and "trees" fields.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 1/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Constructor

In C#, whenever an instance of a class is created, its // Takes two arguments


constructor is called. Like methods, a constructor can
public Forest(int area, string country)
be overloaded. It must have the same name as the
enclosing class. This is useful when you may want to {
define an additional constructor that takes a different this.Area = area;
number of arguments.
this.Country = country;
}

// Takes one argument


public Forest(int area)
{
this.Area = area;
this.Country = "Unknown";
}

// Typically, a constructor is used to


set initial values and run any code
needed to “set up” an instance.

// A constructor looks like a method, but


its return type and method name are
reduced to the name of the enclosing
type.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 2/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Parameterless Constructor

In C#, if no constructors are specified in a class, the public class Freshman


compiler automatically creates a parameterless
{
constructor.
public string FirstName
{ get; set; }
}

public static void Main (string[] args)


{
Freshman f = new Freshman();
// name is null
string name = f.FirstName;
}

// In this example, no constructor is


defined in Freshman, but a parameterless
constructor is still available for use in
Main().

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 3/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Access Modifiers

In C#, members of a class can be marked with access public class Speech
modifiers, including public and private . A public
{
member can be accessed by other classes. A private
member can only be accessed by code in the same private string greeting = "Greetings";
class.
By default, fields, properties, and methods are private,
private string FormalGreeting()
and classes are public.
{
return $"{greeting} and salutations";
}

public string Scream()


{
return FormalGreeting().ToUpper();
}

public static void Main (string[] args)


{
Speech s = new Speech();
//string sfg = s.FormalGreeting(); //
Error!
//string sg = s.greeting; // Error!
Console.WriteLine(s.Scream());
}

// In this example, greeting and


FormalGreeting() are private. They cannot
be called from the Main() method, which
belongs to a different class. However the
code within Scream() can access those
members because Scream() is part of the
same class.

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 4/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Field

In C#, a field stores a piece of data within an object. It public class Person
acts like a variable and may have a different value for
{
each instance of a type.
A field can have a number of modifiers, including: private string firstName;
public , private , static , and readonly . If no access private string lastName;
modifier is provided, a field is private by default.
}

// In this example, firstName and


lastName are private fields of the Person
class.

// For effective encapsulation, a field


is typically set to private, then
accessed using a property. This ensures
that values passed to an instance are
validated (assuming the property
implements some kind of validation for
its field).

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 5/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# this Keyword

In C#, the this keyword refers to the current instance // We can use the this keyword to refer
of a class.
to the current class’s members hidden by
similar names:
public NationalPark(int area, string
state)
{
this.area = area;
this.state = state;
}

// The code below requires duplicate


code, which can lead to extra work and
errors when changes are needed:
public NationalPark(int area, string
state)
{
area = area;
state = state;
}
public NationalPark(int area)
{
area = area;
state = "Unknown";
}

// Use this to have one constructor call


another:
public NationalPark(int area) : this
(state, "Unknown")
{ }

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 6/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Members

In C#, a class contains members, which define the kind class Forest
of data stored in a class and the behaviors a class can
{
perform.
public string name;
public string Name
{
get { return name; }
set { name = value; }
}
}

// A member of a class can be a field


(like name), a property (like Name) or a
method (like get()/set()). It can also be
any of the following:
// Constants
// Constructors
// Events
// Finalizers
// Indexers
// Operators
// Nested Types

C# Dot Notation

In C#, a member of a class can be accessed with dot string greeting = "hello";
notation.

// Prints 5
Console.WriteLine(greeting.Length);

// Returns 8
Math.Min(8, 920);

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 7/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Class Instance

In C#, an object is an instance of a class. An object can Burger cheeseburger = new Burger();
be created from a class using the new keyword.
// If a class is a recipe, then an object
is a single meal made from that recipe.

House tudor = new House();


// If a class is a blueprint, then an
object is a house made from that
blueprint.

C# Property

In C#, a property is a member of an object that public class Freshman


controls how one field may be accessed and/or
{
modified. A property defines two methods: a get()
method that describes how a field can be accessed, private string firstName;
and a set() method that describes how a field can be
modified.
public string FirstName
One use case for properties is to control access to a
field. Another is to validate values for a field. {
get { return firstName; }
set { firstName = value; }
}
}

public static void Main (string[] args) {


Freshman f = new Freshman();
f.FirstName = "Louie";

// Prints "Louie"
Console.WriteLine(f.FirstName);
}

// In this example, FirstName is a


property

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 8/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Auto-Implemented Property

In C#, an auto-implemented property reads and writes public class HotSauce


to a private field, like other properties, but it does not
{
require explicit definitions for the accessor methods
nor the field. It is used with the { get; set; } syntax. public string Title
This helps your code become more concise. { get; set; }

public string Origin


{ get; set; }
}

// In this example, Title and Origin are


auto-implemented properties. Notice that
a definition for each field (like private
string title) is no longer necessary. A
hidden, private field is created for each
property during runtime.

C# Static Constructor

In C#, a static constructor is run once per type, not per class Forest
instance. It must be parameterless. It is invoked before
{
the type is instantiated or a static member is accessed.
static Forest()
{
Console.WriteLine("Type
Initialized");
}
}
// In this class, either of the following
two lines would trigger the static
constructor (but it would not be
triggered twice if these two lines
followed each other in succession):
Forest f = new Forest();
Forest.Define();

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 9/10
10-02-2024 16:04 Learn C#: Learn C#: Classes and Objects Cheatsheet | Codecademy

C# Static Class

In C#, a static class cannot be instantiated. Its //Two examples of static classes calling
members are accessed by the class name.
static methods:
This is useful when you want a class that provides a set
of tools, but doesn’t need to maintain any internal data.
Math is a commonly-used static class. Math.Min(23, 97);
Console.WriteLine("Let's Go!");

Print Share

https://www.codecademy.com/learn/learn-c-sharp/modules/learn-csharp-classes/cheatsheet 10/10

You might also like