Saturday, April 20, 2019 04:27

Methods and functions signature

I talked in the previous lesson about methods and functions signatures, and I offered there a brief explanation on the topic. It is time to explain this new concept in more detail. At a basic level, there are only two things that are mandatory to specify a method or function signature: the parameters type and the order in which the parameters are listed.

Keep in mind that the names of the parameters are not important for the method or function declaration. This means that:

The reason why the above example will not work is because even if we named our method’s parameters differently, their type and order is actually the same, so we say that the the two DoSomething() methods signatures are identical. They both declare an int and a float parameters, in the same exact order. This is why the compiler will display the following error: Type ‘your_class_name’ already defines a member called ‘DoSomething’ with the same parameter types.

It would be enough to simply change the position of one of the parameters or change its type for the error to disappear. In this case, we would create an overload of our method.

So, in the following example, all declarations will work, because their signatures are different:

This is true for methods, but can actually the return type of a function change anything? Let’s see:

So, we have two functions, with identical parameters (both as their type and their position), but with different return types – one returns an int, while the other returns a long. Is this enough for creating a different signature?

Sadly, no. Even if the functions return different types of data, they expect the same parameters type, which means that when we call the function, the compiler simply doesn’t know which one of the functions we are trying to call, and hence, will display an error: The call is ambiguous between the following methods or properties: ‘Sum(int, int)’ and ‘Sum(int, int)’.



Tags: , , , , ,

Leave a Reply