Start learning free

LESSON 287 OF 674 · FUNCTIONS & CLASSES

Class Methods in C#

Lesson

TL ; DR:

  • A method is a function that lives inside a class. Each object can call its methods, and the methods can read and write the object's fields.


  • Define a method like a regular function, but inside the class body:

    class Dog {
        public string name;
    
        public void Bark() {
            Console.WriteLine("Woof! I am " + name);
        }
    }
    

  • Call it on an object with the dot operator: dog.Bark();



Full lesson:

So far you've added data to a class with fields and constructors. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


Defining a method

class Dog {
    public string name;

    public void Bark() {
        Console.WriteLine("Woof! I am " + name);
    }
}

Notice that Bark() can directly read the name field — no this. needed because there's no naming conflict. Each Dog object has its own name, and when you call rex.Bark(), the method sees rex's name.


Calling a method

Dog rex = new Dog("Rex");
rex.Bark();   // prints: Woof! I am Rex

Your task

The Dog class already has a name field and a constructor. Add a Bark() method that prints "Woof! I am " followed by the dog's name. The pre-filled code creates a Dog named "Rex" and calls Bark().

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check