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:
1 2 3 |
// These two declarations will cause an error static void DoSomething(int param1, float param2) { } static void DoSomething(int p1, float p2) { } |
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:
1 2 3 4 |
static void DoSomething(int param1, float param2) { } static void DoSomething(int param1, int param2) { } static void DoSomething(float param1, int param2) { } static void DoSomething(float param1, float param2) { } |
This is true for methods, but can actually the return type of a function change anything? Let’s see:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
static void Main(string[] args) { Console.WriteLine(Sum(2, 3)); Console.Read(); } static int Sum(int a, int b) { return a + b; } static long Sum(int a, int b) { return a + b; } |
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)’.
The concepts explained in this lesson are also shown visually as part of the following video:
Tags: functions, functions parameters, methods, methods declaration, methods parameters, signatures