recherche

Hi!

In the following method overloading, the method call, "mc.myMethod(0)" calls only the method with int parameter, why How to call the other methods using the same method call

using System;

class MyClass
{
public void myMethod(sbyte a)
{
Console.WriteLine("Parameter sbyte: a = {0}", a);
}

public void myMethod(byte a)
{
Console.WriteLine("Parameter byte: a = {0}", a);
}

public void myMethod(short a)
{
Console.WriteLine("Parameter short: a = {0}", a);
}

public void myMethod(ushort a)
{
Console.WriteLine("Parameters ushort: a = {0}", a);
}

public void myMethod(int a)
{
Console.WriteLine("Parameter int: a = {0}", a);
}

public void myMethod(uint a)
{
Console.WriteLine("Parameter unint: a = {0}", a);
}

public void myMethod(long a)
{
Console.WriteLine("Parameter long: a = {0}", a);
}

public void myMethod(ulong a)
{
Console.WriteLine("Parameter ulong: a = {0}", a);
}
}


class MainClass
{
static void Main()
{
MyClass mc = new MyClass();

mc.myMethod(0);
}
}

Thank you.



Re: Visual C# General C#, method overloading

Mattias Sjogren

Use a cast at the call site, i.e.

mc.myMethod((byte)0);






Re: Visual C# General C#, method overloading

recherche

Casting is fine by me! I am asking why the method call invokes only the method with int parameter, why not short etc





Re: Visual C# General C#, method overloading

tkrasinger

because if you just write "0" the value is interpreted as integer. You will have to cast if (or use a postfix) so that the Compiler notices it is not an int.

Same if you write 1.23 it will always be a double, if you want it to be a decimal or float, you will have to cast it.





Re: Visual C# General C#, method overloading

Matthew Watson

Or, for floats, put a suffix at the end: 1.234 = double, 1.234f = float, 1.234m = decimal.


[edit: Corrected decimal suffix, an error that was pointed out by the message below!]




Re: Visual C# General C#, method overloading

boban.s

Matthew Watson wrote:
Or, for floats, put a suffix at the end: 1.234 = double, 1.234f = float, 1.234d = decimal.

small correction:

double: none or d, D
float: f, F
decimal m, M
int: none
long: l, L
unsigned types: u, U

l and u can be combined like 'lu' will means ulong.




Re: Visual C# General C#, method overloading

Chad Moran

Now I'm not saying you should stop using what you're using but you may want to take a peek into generics.

example...


Code Snippet

public void MyMethod<T>(T obj)
{

Console.WriteLine(obj.GetType().Name);

}

I typed that in the forum post textbox so if it's incorrect somewhere I apologize.