Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to overload methods with different parameter types in C#

Tags:

c#

overloading

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.

like image 752
Hamid Avatar asked Feb 16 '26 11:02

Hamid


2 Answers

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;

like image 196
Michael Stum Avatar answered Feb 18 '26 23:02

Michael Stum


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);
    }
like image 21
Bala R Avatar answered Feb 19 '26 01:02

Bala R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!