Overloading and Resolution - CSharp Custom Type

CSharp examples for Custom Type:overload

Introduction

Consider the following two overloads:

static void Foo (Item a) { }
static void Foo (Company h) { }

When an overload is called, the most specific type has precedence:

Company h = new Company (...);
Foo(h);                      // Calls Foo(Company)

The overload to call is determined at compile time rather than at runtime.

The following code calls Foo(Item), even though the runtime type of a is Company:



public class Item
{
  public string Name;
}

public class Stock : Item   // inherits from Item
{
  public long SharesOwned;
}

public class Company : Item   // inherits from Item
{
  public decimal Mortgage;
}
     
     
     
Item a = new Company (...);
Foo(a);                      // Calls Foo(Item)

Related Tutorials