Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an alias for a function name in C#

Tags:

c#

alias

I want to create an alias for a funcion name in C#.

Is there any way but function overloading?

public class Test
{
    public void A()
    {
        ...
    }
}

I want to call B replace A same below.

var test = new Test();
test.B();
like image 239
Ghooti Farangi Avatar asked May 22 '11 14:05

Ghooti Farangi


2 Answers

I'm surprised that noone has mentioned Delegates. It's probably as close to a method alias as you will come in C#:

class DelegaTest
{
    public string F()
    {
        return null;
    }

    public string F(int arg)
    {
        return arg.ToString();
    }

    public void G(int arg1, int arg2)
    {
    }

    /// <summary>
    /// Delegate for `string F()`
    /// </summary>
    public Func<string> D1 => F;

    /// <summary>
    /// Delegate for `string F(int arg)`
    /// </summary>
    public Func<int, string> D2 => F;

    /// <summary>
    /// Delegate for `void G(int arg1, int arg2)`
    /// </summary>
    public Action<int, int> E => G;
}
like image 112
Christian Davén Avatar answered Nov 11 '22 06:11

Christian Davén


You can use an extension method

public static class Extensions 
{
    public static void B(this Test t)
    {
       t.A();
    }
}

But it is not an alias. It is a wrapper.


EDIT
ps: I agree with the commenters on your question that we'd be able to give better answers if we knew what you really wanted to do, if we understood the problem you're trying to solve.

I don't really see the point of producing the above extension method.

like image 38
Cheeso Avatar answered Nov 11 '22 05:11

Cheeso