C# out parameter in extension method
Asked Answered
T

2

5

In an extension method, I am receiving an error that my 'out' parameter does not exist in the current context. I assume this means that extension methods cannot have 'out' parameters, but this is not specified in the documentation. I would appreciate it if someone could please clarify!

public static int customMax(this int[] data, out index)
{
    int max = data[0];
    index = 0;

    for (int i = 1; i < data.Length; i++) {
        if (data[i] > max) {
            max = data[i];
        }
    }

    return max;
}
Tolley answered 23/8, 2015 at 6:20 Comment(2)
you forgot add type (int, i think) for your index parameterFossick
You also forgot to set the actual value to be returned via index.Copywriter
S
7

Extension methods can have out parameters. You need to specify the type of your out parameter. So change code

public static int customMax(this int[] data, out index)

to

public static int customMax(this int[] data, out int index)

and it should all work

Suspire answered 23/8, 2015 at 6:22 Comment(1)
Thanks - I noticed this and was going to remove the question, but you were too quick!Tolley
C
0

You've missed specifying the type on the out parameter. It should read:

    public static int customMax(this int[] data, out int index)

There is some conjecture you might be interested in on another question, regarding the readability of doing this kind of thing. Impossible to use ref and out for first ("this") parameter in Extension methods?

Cookout answered 23/8, 2015 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.