C Sharp/Overloading

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control
C# - Variables II
C# - Functions and Methods

C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

[edit] C# Function Overloading

Overloading is the idea of having multiple functons that are the same name. Each function must accept different types or amount of types. This is how the compiler differentiates from overloaded functions.


Example 1:

using System;
class Program
{
    static void Function(int x) //Accepts an int
    {
        x = 12;
        Console.WriteLine(x + " is an int");
    }
    static void Function(long x)  //Accepts a long
    {
        Console.WriteLine(x + " is an long");
    }
    static void Main()
    {
        int a = 12;
        long b = 12;
        Function(a);  //passing an int value
        Function(b);  //passing a long value
        Console.Read();
    }
}

Output:

12 is an int
12 is a long

Example 2:

using System;
class Program
{
    static void Function(int x)  //Accepts one parameter
    {
        x = 12;
        Console.WriteLine(x + " is an int");
    }
    static void Function(int x, int y)  //Accepts two parameters
    {
        Console.WriteLine(x + " and " + y + " are int");
    }
    static void Main()
    {
        int a = 12;
        int b = 12;
        int c = 12;
        Function(a);  //passing one value
        Function(b, c);  //passing two values
        Console.Read();
    }
}

Output:

12 is an int
12 and 12 are int

The are more ways to give the compiler hints that functions are different. These are just a couple of ways I have presented. C# function overloading is a powerful tool. With overloading your code will be somewhat shorter and can decrease development time. Overloading does not have any performance benefits infact it has a minute performance hit because the compiler must choose which function to call. This decision takes a very small amount of time.