Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0103 Method overloading

Methods can have the name but different parameter types. The following code defines a class, Math. Math has two methods with the same name. It is legal since the signatures are different. using System; class Math { public static int add(int i, int j) { return i + j; } public static float add(float f, float f2) { return f + f2; } } class Program { static void Main(string[] args) { Console.WriteLine(Math.add(1, 2)); Console.WriteLine(Math.add(1.1F, 2.2F)); } } params is not part of the signature. class Math{ static void sum(int[] anArray){ } static void sum(params int[] anArray){ } } Compile-time error C:\g>csc Program.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(9,17): error CS0111: Type 'Math' already defines a member called 'sum' with the same parameter types Program.cs(5,17): (Location of symbol related to previous error) The return type is not part of the signature. class Math{ int add(int i, int j){ return i+j; } float add(int i, int j){ return (float)(i+j); } } Compile-time error. C:\g>csc Program.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. Program.cs(9,11): error CS0111: Type 'Math' already defines a member called 'add' with the same parameter types Program.cs(5,9): (Location of symbol related to previous error)