Skip to content
← Back to Community
Method Overloading
Profile icon
ANDREWVOSS

I posted this a couple hours ago in Share and then took it down and moved it to Tutorials because I felt like it was more of a tutorial than anything. Anyways, enjoy!

Method Overloading

In C#, the arguments that a function uses as well as the output it returns have to be a specific variable type. For example,

static int myFunc(int input) { return(input*2); }

This function multiplies the input by 2, but only if that input is an int.
If we try to use this function with a double input, it will return an error.
We could use this code:

static double myFunc(double input) { return(input*2); }

But then, if we try to input an int, then it will return an error.
However, there is a solution. Method overloading is a technique that allows us to have multiple different versions of a function that have different inputs and outputs.

//function takes int for input and outputs int static int myFunc(int input) { return(input*2); } //function takes double for input and outputs double static double myFunc(double input) { return(input*2); } //function takes string for input and outputs string static string myFunc(string input) { return("that's not a number"); }

As you can see, there are three functions with the same name.
If we call the function with an int, it returns the int version of the function. Same for the double and string versions.

int x = 1; myFunc(x); //returns int 2 double y = 1.1; myFunc(y) //returns double 2.2 string z = "hello"; myFunc(y) //returns string "that's not a number"

So, when we have an overloaded function, we can call it later and it will change automatically based on the type of input.

Thanks for reading!

Check the source code or ask me if you don't understand something.

Voters
Profile icon
DynamicSquid
Profile icon
ANDREWVOSS
Comments
hotnewtop
Profile icon
ZarifAhmed2

Would there be a way to make it so that I could input a string in the int section and it will still function properly (ex. it asks for an int, I input a string, the code still works) or is that not possible?