use extension method to provide global function for c#

Coordinator
May 23, 2014 at 10:36 AM
Edited May 23, 2014 at 10:37 AM
just a tricky, example below,
using System;

public static class _extension
{
    public static int func(this object i)
    {
        return ReferenceEquals(i, null) ? 0 : 1;
    }

    public static int func2(this object i, int x, int y)
    {
        return x + y;
    }
}

public static class _main
{
    private static void run<T>(T i)
    {
        Console.WriteLine(i.func());
        Console.WriteLine(i.func2(1, 2));
    }

    private class C
    {
    }

    public static void Main()
    {
        run(new int());
        run("abc");
        run(new object());
        run((string)null);
        run((object)null);
        run(new C());
        run((C)null);
    }
}
and you can also write the extension functions in a single file, and import namespace when you need them