Method Overloading

C# allows methods to share the same name but differ in the number and/or types of parameters.  This is called
method overloading and is common practice in C++ and Java programming.

You cannot overload methods that only differ by the return type.


// Some overloading examples...

static int Add(int n1, int n2)
{ return n1 + n2; }

static int Add(int n1)
{ return n1+n1; }

static double Add(double n1, double n2)
{ return n1 + n2; }

// Compile error! Cannot differ by return type only.

static double Add(int n1, int n2)
{ return n1 + n2; }

// OK! Parameter modifiers do differentiate methods.

static double Add(int n1, ref int n2)
{ return n1 + n2; }


The runtime can tell which Add method to invoke based on the type or number of parameters passed to the
method.


static void Main(string[] args)
{
  // Calls Add(int, int)
  int i = Add(1, 2);

  // Calls Add(int)
  int j = Add(i);

  // Calls Add(double, double)
  double d = Add(5.7, 2.1);

  // Calls Add(int, ref int)
  d = Add(9, ref i);
}



Unlike C++, C# does not allow you to specify default values for parameters.  C++ default parameters often lead
to ambiguities between overloaded methods and methods with default parameters.  In C#, use method
overloading to substitute for default parameters.


static int Add(int x, int y, int z)
{ return x + y + z; }

static int Add(int x, int y)
{

  // Assign default value to z.

  int z = 5;
  return Add(x, y, z);
}

Overloading
Table of Contents
C# Tutorial | C#.NET Tutorial | Overloading Tutorial

exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services