Which Function Gets Called When? The difficult part when overloading functions is trying to figure out which function the compiler is going to call. Consider the code in Figure 6.5 . The code in that figure has three functions: one that accepts a double, one that accepts a float, and one that accepts any object. (All types are compatible with the object type.) The code calls MakeDeposit but passes an integer as the parameter. Which of the functions gets called? The rules are described in the C# ECMA Specification under section 14.4.2 Overload Resolution. However, the short version of the rules is that functions are selected based on which function results in a better conversion. Essentially, a better conversion is one where the type you are converting to is closest in memory consumption to the type you are starting from. So in the case of numeric values one can follow the following list: byte, short, int, long, float or decimal, double, object. In this list, byte consumes the least amount of memory and object consumes the most. You pick the smallest type that fits the value you are converting without data loss. In C# all literal integral numbers are of type int by default. However if there is no integer function to invoke, C# checks to see if the number is within the range of a smaller data type (short for example). All decimal numbers are of type double by default. In Figure 6.5 , the closest data type is float. Figure 6.5 Decisions, decisions. The 500 value is type integer, so which of the MakeDeposit version actually gets called? The answer is double. Double is the closest data type to Integer, memory-wise. class Account { public void MakeDeposit(double Amount) { } public void MakeDeposit(float Amount) { } public void MakeDeposit(object Amount) { } } class Bank { public void CreateAccount() { Account acct = new Account(); acct.MakeDeposit(500); } } |