C# Class Members

Everything you put inside a class is called a class member. The two members you will use most often are fields, which store data, and methods, which describe behavior. This lesson shows how they work together inside a single class.

Fields

A field is a variable declared directly inside a class. Fields hold the data that describes an object, such as a car's color or maximum speed. You can give a field a default value, and you can change its value through an object after you create it.

A class with fields

class Car
{
    public string model;
    public int maxSpeed = 200;
}

class Program
{
    static void Main()
    {
        Car myCar = new Car();
        myCar.model = "Mustang";
        Console.WriteLine(myCar.model);
        Console.WriteLine(myCar.maxSpeed);
    }
}
// Output:
// Mustang
// 200

Methods

A method is a block of code inside a class that performs an action. Methods let objects do things. You call a method on an object using the dot operator followed by the method name and parentheses. Methods can read and change the object's own fields.

A class with a method

class Car
{
    public string model = "Mustang";

    public void StartEngine()
    {
        Console.WriteLine(model + " engine started.");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car();
        myCar.StartEngine();
    }
}
// Output:
// Mustang engine started.

Fields and Methods Together

Real classes combine fields and methods so that an object holds data and knows how to use it. In the example below, the field stores the speed and the method changes and reports it.

Member typePurposeExample
FieldStores data about the objectpublic int speed;
MethodDefines an action the object can dopublic void Accelerate() { ... }

Data and behavior in one class

class Car
{
    public int speed = 0;

    public void Accelerate(int amount)
    {
        speed += amount;
        Console.WriteLine("Speed is now " + speed);
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car();
        myCar.Accelerate(30);
        myCar.Accelerate(20);
    }
}
// Output:
// Speed is now 30
// Speed is now 50
Note: Notice that a method inside the class can use a field by name directly, without the dot operator. The dot operator is only needed when you access members from outside the class, through an object.