What is the difference between Methods and Functions?

I want to ask two questions:
First,
Is there any difference between a method and a function? If there was, what is it?

Second,
We used void because it returns nothing. If a method returns something, what is it like?(I want an example)

Thanks.

Hello Mohammed, welcome to the community :slight_smile:

The terms method and function are often used interchangeably and it is unlikely that anyone would pick you up on it, however, strictly speaking;

Function

A piece of code, called by name. It may or may not have parameters passed to it.

Method

A method is also a piece of code, called by name. It also may, or may not, have parameters passed to it. It is implicitly passed the object on which it was called. It can operate on non-public data contained within the class.

Depending on the language you use to write code in there may be some other subtleties, for example, in C++ methods may be referred to as member functions. Member being a reference to something belonging to a class.


With regards to void, this is the type which is returned by your method/function. To return other types you just specify those types instead of void. For example;

public int GetSumOfTwoNumbers(int firstNumber, int secondNumber)
{
    int sum;

    sum = firstNumber + secondNumber;

    return sum;
}

In the above example, we have defined int as the return type, whatever this method/function does, needs to return an object of that type. For clarity, I have written this in a longer way, but equally, you could have written it like this;

public int GetSumOfTwoNumbers(int firstNumber, int secondNumber)
{
    return firstNumber + secondNumber;
}

The reason you can do this is that both of the parameters being passed in have to be of type int also, as per the definition of the method/function.

Hope this helps :slight_smile:


See also;

thanks

You’re welcome :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.