Start learning free

LESSON 183 OF 347 · OBJECT-ORIENTED PROGRAMMING

Class Methods in C#: Giving Objects Behavior

Lesson Read the full explanation

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

    C# · OBJECT-ORIENTED PROGRAMMING

    Class Methods in C#, explained

    What a method is

    Fields and constructors give an object data. The other half of object-oriented programming is behaviour: things an object can do. A method is a function that lives inside a class. It can read and change the fields of the object it is called on.

    Defining a method

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

    A method declaration has these parts, from left to right:

    • public, the access modifier, so that code outside the class may call the method. Without a modifier, a method is private.
    • void, the return type. It means the method does something but gives nothing back. A method that produces a value names that type instead, for example string or int.
    • Bark, the name. C# convention is PascalCase for method names, so Bark, not bark.
    • The parentheses, which hold the parameters. This method needs none.
    • The body in curly braces.

    Inside Bark, the code reads name directly. It doesn't need this.name, because nothing else called name is in the way. Each Dog has its own name, and the method sees the name of the dog it was called on.

    Calling a method

    Use the dot operator on an object, followed by the method name and parentheses:

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

    The parentheses are needed even when there are no arguments. Without them, rex.Bark names the method but doesn't run it.

    Two dogs share the method but not the data:

    Dog luna = new Dog();
    luna.name = "Luna";
    luna.Bark();   // Woof! I am Luna
    

    Parameters and return values

    Methods become more useful once they take input and give output:

    class Dog {
        public string name;
        public int age;
    
        public void Birthday() {
            age++;
        }
    
        public int HumanYears() {
            return age * 7;
        }
    
        public string Describe(string greeting) {
            return greeting + ", " + name;
        }
    }
    

    Birthday changes the object's state, HumanYears returns a value computed from it, and Describe takes a parameter. A method with a non-void return type must return a value on every path through it.

    Common mistakes

    • Forgetting public. A method with no modifier is private. Calling rex.Bark() from Solution then fails with an error saying Dog.Bark() is inaccessible due to its protection level.
    • Lowercase names. C# is case-sensitive. The lesson calls rex.Bark(), so a method called bark doesn't match. Code ported from Java or Python often uses lowercase method names, but C# uses PascalCase.
    • Printing instead of returning, or the other way round. A void method that prints can't be used inside an expression. A method that returns a value prints nothing unless the caller does.
    • Calling on the class instead of an object. Dog.Bark() fails for an ordinary method, because it needs a particular dog's name.
    • Using this when it isn't needed. It's allowed and harmless: this.name means the same as name here. It becomes necessary only when a parameter or local variable has the same name as the field.

    The exercise, step by step

    The Dog class already has a name field and a constructor. The code in MainFunction creates a dog named "Rex" and calls rex.Bark(), but Bark doesn't exist yet. The expected output is:

    Woof! I am Rex
    
    1. Declare an empty method below the constructor: public void Bark() { }. It is public so that Solution may call it, and void because it only prints.
    2. Fill in the body. Print "Woof! I am " joined with the name field using +.
    class Dog {
        public string name;
    
        public Dog(string name) {
            this.name = name;
        }
    
        public void Bark() {
            Console.WriteLine("Woof! I am " + name);
        }
    }
    
    class Solution {
        public void MainFunction() {
            Dog rex = new Dog("Rex");
            rex.Bark();
        }
    }
    

    When rex.Bark() runs, the field name inside the method refers to rex's name, which the constructor set to "Rex".

    Key takeaways

    • A method is a function declared inside a class; it can use the object's fields.
    • The usual shape is an access modifier, a return type, a PascalCase name, parameters and a body.
    • Call it on an object with the dot operator and parentheses.
    • Methods share code, while fields hold each object's own data.
    • Add public to methods that other classes should call.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free