Class methods

Teaches you the role of a method in a class, definining and using a method and method overloading.

Classes are composed of fields and methods. I suppose you already know what a field is therefore we’ll talk about methods here.

An entity can have properties and can perform certain actions.
For example a human can have several properties like age, sex and eye color. Also it can perform some actions, like walking, talking or cooking.

In a class, the properties are called simply properties or fields or member variables (although you should already know that) and the action it can perform are called methods.

Here is how we can define a method:


void walk(string destination)
{
Console.WriteLine("The human walks toward {0}.", destination);
// Other code for making the human walk
}



We use ‘void’ because we don’t want the method to return any value. If we wanted it to return a value we would use ‘int’, ‘double’ or whatever type of value we returned.

Next is the name of the method. We want a method that makes the human walk… unfortunately we can’t program a real human (yet)  so we’ll have to do with this fictional example.

In the parenthesis following the name of the method we have ‘string destination’. This is called a parameter. ‘string’ is the type of parameter and ‘destination’ is the name of the parameter.

Parameters are values passes to the method. If you have just a bit of experience with C++ (or other programming languages) functions you should already know this.

Inside the method we have a line of code that prints a line in the MS-DOS prompt and uses the parameter ‘destination’ to display the destination where the human should go.

How does this work? Let’s see the full code, how we create an object (an instance) of the ‘human’ class:


using System;

class human
{
int age;
string sex;
string eyeColor;
        void walk(string destination)
        {
        Console.WriteLine("The human walks toward {0}.", destination);
        }
}
class Class1
{
        static void Main()
    {
        human JohnDoe = new human();
            JohnDoe.age = 36;
        JohnDoe.sex = "male";
            JohnDoe.eyeColor = "blue";
        JohnDoe.walk("home");
    }
}



As you can see we create an object ‘JohnDoe’ of type human using ‘human JohnDoe = new human()’.
Next we complete different field about our human named JohnDoe, like age, sex and color of the eyes.
Next comes the method. We call the method similar to a field, with the exception that we pass a parameter.
As you probably guessed, the string ‘home’ passed as a parameter is actually the value of the variable ‘destination’. Wherever we used ‘destination’ inside the method we actually use the ‘home’ string.
This is why:


Console.WriteLine("The human walks toward {0}.", destination);



prints


The human walks toward home.



in the console.

When you pass a variable to the method you pass it by value, that means the original variable is not modified.
If you want to pass the variable by reference, so that the original value gets modified too, use ‘ref’ before the parameter:


void walk(ref string destination)
{
}



Next is an example of a method that returns a value:


using System;

class calculator
{
    public int add(int x, int y)
    {
        return x + y;
    }
}
class Class1
{
    static void Main()
    {
        calculator homework = new calculator();
        int addition = homework.add(3, 4);
        Console.Write("Result is {0}.", addition);
    }
}

Overloading a method

In a class defining a method identical to another method in that class isn’t allowed, it generates a compiler error.
Although, you can create a method with the same name as some other method in that class but with different parameters. This is called overloading a method.
The overloaded method should have parameters of different name or type, or at least a different number of parameters.


class human
{

        // overloaded method
        void walk(string destination)
        {
        Console.WriteLine("The human walks toward {0}.", destination);
        }

        // overloaded method
        void walk(int coordinate)
        {
        Console.WriteLine("The human walks toward the {0} coordinate.", coordinate);
        }

        // overloaded method
        void walk(int coordinate, string destination)
        {
        Console.WriteLine("The human walks toward the {0} using the {1} coordinate.", destination, coordinate);
        }
}



The compiler knows which overloaded method you use by the context, that is the name, type and number of arguments you pass.

You can’t overload methods by changing the return type. Why, you cry? Let’s see the following examples:


int walk();
long walk();



In the following case the compiler understands which method you wish to use because of the context… you store the result (return value) in an int variable, therefore it will use ‘int walk()’ method.


int result = walk()



Although, when you call the method without storing the result in a specific type variable the compiler doesn’t know which method to choose:


walk()

There are some other things to say about methods. This tutorial wanted to be an extra to the chapter about methods that your C# book covers, because sometimes you don’t understand method overloading from the first shot, although you now know it’s very simple.

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top