Hamid
Hamid

Reputation: 478

how to overload methods with different parameter types in C#

I'm trying to overload a method in C# with the same number of parameters but different types.

private double scale(double value) 
{
    return value * 100 / scale;
}

private float scale(float value)
{
    return value * 100 / scale;
}

but I get this error

Error 4 The type '[className]' already contains a definition for 'scale'

NOTE: I'm working in MVS 2008

Thank you.

Upvotes: 2

Views: 7550

Answers (5)

Michael Stum
Michael Stum

Reputation: 181104

This code doesn't make sense:

return value * 100 / scale;

If you have a method name scale, then what does the scale at the end of the line do?

Your Method Signature is semantically correct, as this is perfectly legal C# code:

private float scale(float input)
{
    return input;
}

private double scale(double input)
{
    return input;
}

It seems that you also have a field or property named scale in your class:

private float scale = 0.15f;

Upvotes: 7

Dark_M
Dark_M

Reputation: 11

You can use Generics.

private T scale<T>(T value) where T: struct
{
    return value * 100 / scale;
}

You can replace T with float or double or any struct.

Upvotes: 0

Jonathan Wood
Jonathan Wood

Reputation: 67345

I think this is going to give you trouble. If the argument is, for example, 1.5, how will the compiler know if you are passing a float or a double?

I would just stick with double unless you have special needs here.

Upvotes: 1

Marino Šimić
Marino Šimić

Reputation: 7340

Can it be that you are calling a member variable the same as a method?

float scale2;
private double scale(double value)
{
    return value * 100 / scale2;
}

private float scale(float value)
{
    return value * 100 / scale2;
}

This compiles, however you probably want the same return type.

Upvotes: 1

Bala R
Bala R

Reputation: 109027

To me it's complaining about the scale that you are using as a variable. You can have something like this

    private double scale1 =  0.0d;
    private double scale(double value)
    {
        return value * 100 / scale1;
    }

    private float scale(float value)
    {
        return (float) (value * 100 / scale1);
    }

Upvotes: 2

Related Questions