Loading lessons...
Class Members & Multiple Objects
Fields and methods that belong to a class are called its members.
Fields and methods
A class can hold fields (data) and methods (behavior):
csharp
class Car
{
string color = "red";
int maxSpeed = 200;
public void fullThrottle()
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
### Car myObj = new Car();
### Console.WriteLine(myObj.color); // red
### Console.WriteLine(myObj.maxSpeed); // 200
myObj.fullThrottle();
}
}
Accessing members
Use dot notation - object.member:
csharp
myObj.color
myObj.fullThrottle()
Multiple objects
You can create as many objects as you need, and each keeps its own copy of the fields:
csharp
class Car
{
string color = "red";
static void Main(string[] args)
{
### Car myObj1 = new Car();
### Car myObj2 = new Car();
### Console.WriteLine(myObj1.color); // red
### Console.WriteLine(myObj2.color); // red
}
}
The public keyword
public makes a member accessible from other classes. Members without public are private by default - you'll learn more about access modifiers soon.
TL;DR
- Fields hold data; methods define behavior.
- Use dot notation:
object.member. - Every object has its own copy of the fields.
publicopens members to other classes.