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 examplestringorint.Bark, the name. C# convention is PascalCase for method names, soBark, notbark.- 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. Callingrex.Bark()fromSolutionthen fails with an error sayingDog.Bark()is inaccessible due to its protection level. - Lowercase names. C# is case-sensitive. The lesson calls
rex.Bark(), so a method calledbarkdoesn'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
voidmethod 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
thiswhen it isn't needed. It's allowed and harmless:this.namemeans the same asnamehere. 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
- Declare an empty method below the constructor:
public void Bark() { }. It ispublicso thatSolutionmay call it, andvoidbecause it only prints. - Fill in the body. Print
"Woof! I am "joined with thenamefield 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
publicto methods that other classes should call.