Learn C#: Classes and Objects
Define your own custom types using classes.
StartKey Concepts
Review core concepts you need to learn to master this subject
C# Classes
C# Constructor
C# Parameterless Constructor
C# Access Modifiers
C# Field
C# this Keyword
C# Members
C# Dot Notation
C# Classes
C# Classes
using System;
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.
In C#, classes are used to create custom types. The class defines the kinds of information and methods included in a custom type.
Basic Classes and Objects
Lesson 1 of 2
- 1With data types like int, string, and bool we can represent basic data and perform basic operations: int count = 32; count++; What if we want to represent something more complex — somethin…
- 2C# provides built-in data types, like string: each instance of the string type has its own values and functionality. string phrase = “zoinks!”; Console.WriteLine(phrase.Length); Console.WriteLine(…
- 4As of now, a program can plant any value in a Forest field. For example, if we had an area field of type int, we could set it to 0, 40, or -1249. Can we have a forest of -1249 area? We need a way t…
- 5It might have felt tedious to write the same getter and setter for the Name and Trees properties. C# has a solution for that! The basic getter and setter pattern is so common that there is a short…
- 6At this point we have built fields to associate data with a class and properties to control the getting and setting of each field. As it is now, any code outside of the Forest class can “sneak past…
- 7Previously we used properties for field validation. By applying public and private, we can also use properties to control access to fields. Recall our imaginary Area property. Say we want program…
- 9In each of the examples so far, we created a new Forest object and set the property values one by one. It would be nice if we could write a method that’s run every time an object is created to set …
- 11Just like other methods, constructors can be overloaded. For example, we may want to define an additional constructor that takes one argument: public Forest(int area, string country) { this.Ar…
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