Why can't I have two method signatures with the only difference being the "params" keyword for the array parameter? [duplicate]
Asked Answered
M

2

5
public class SomeClass
{
    public SomeClass(SomeType[] elements)
    {
        
    }
    public SomeClass(params SomeType[] elements)
    {
        
    }
}

I printed this code and got CS0111 error. I'm surprised, are SomeType[] elements and params SomeType[] elements the same arguments?

Mickelson answered 19/9, 2022 at 14:0 Comment(4)
Both constructors have the same signature. params keyword does not change method signature.Contemplation
params is not the part of the signature of the function.Mariandi
#27376207Shrug
Note that params is just a metadata keyword for the C# compiler and has no bearing on the method signature nor on the compilation of the method itself. Basically, params is just an instruction for the compiler regarding call sites (i.e. callers) of this method to translate a method call in source code like SomeFooWithParams(1, 2, 3, 4) into SomeFooWithParams(new[] { 1, 2, 3, 4 }) (for simplicity, lets ignore right now any other non-params parameters a method might declare...)Powers
C
2

The difference between the two is that one requires a single concrete array, while the other also allows it to be called with individual items such as

SomeClass("Alpha", "Omega", "Gamma")

Choose the params one if you need to call it as above and delete the other.

Why?

The error speaks to the fact that both are, to the compiler, the same signature SomeType[] hence the error.

Contessacontest answered 19/9, 2022 at 14:3 Comment(0)
X
5

Yes, params does not make the parameter into a different type. Both translate to an array of SomeType.

Xerox answered 19/9, 2022 at 14:1 Comment(0)
C
2

The difference between the two is that one requires a single concrete array, while the other also allows it to be called with individual items such as

SomeClass("Alpha", "Omega", "Gamma")

Choose the params one if you need to call it as above and delete the other.

Why?

The error speaks to the fact that both are, to the compiler, the same signature SomeType[] hence the error.

Contessacontest answered 19/9, 2022 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.