18

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();
demongolem
  • 9,474
  • 36
  • 90
  • 105
Ghooti Farangi
  • 19,926
  • 15
  • 46
  • 61
  • Also if you're overloading something, you're not aliasing it since it's the same identifier. – BoltClock May 22 '11 at 14:41
  • 4
    You're presenting us with a (broken?) solution, to some problem that you're encountering. We'd probably do a lot better if you told us what the *problem* is that you're trying to solve. – Damien_The_Unbeliever May 22 '11 at 14:46
  • 2
    So, the real answer is: `No, C# does not have method aliasing`. Why is is to hard to give straight forward answer? – CoR Dec 13 '16 at 09:15

9 Answers9

32

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;
}
Christian Davén
  • 16,713
  • 12
  • 64
  • 77
  • Can you additionaly show: 1) with overloads support 2) with arguments, but void type – T.Todua Feb 26 '19 at 19:08
  • @T.Todua, I have added some examples and modified to work with C# 7.0 (fat arrow). – Christian Davén Feb 27 '19 at 07:01
  • Seems like there is no advantage of this approach over separate methods that cascade the calls. Except the methods would be far more efficient than this because `Func<>` and `Action<>` allocate extra memory that regular methods do not. – NightOwl888 Jul 06 '21 at 08:32
  • Nice, but is there any way to use that with an optional parameter passed to a function? – Marcin Aug 31 '21 at 13:57
  • public Func> React => SetBillStatusAsync; public async Task SetBillStatusAsync(string itemId, OrderPaymentStatus status) { return await _api.SetBillStatusAsync(itemId, status); } – Nick Kovalsky Apr 10 '22 at 06:11
13

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.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • Unfortunately, this isn't helpful if the method you want to alias is static. But this approach works well for instance methods, especially if they are only syntactic sugar for compatibility reasons, in which you can put them in a namespace that is optional to import. – NightOwl888 Jul 06 '21 at 08:34
  • The point of the alias, especially for those from Ruby backgrounds - is to make their life easier. I have a method called `minus`. I want to alias another called `subtract`. I was hoping c# with have some syntactic sugar to do that. No big deal to create a wrapper but that's why. – BenKoshy Dec 09 '22 at 00:12
10

This is so old, but I have a response as to why a person may want to alias a method name. It happens all the time. Because some developer has given a method a name that does not make any sense or it simply does not accurately describe the purpose of the method. The method is called many times throughout an old, well-seasoned solution. So rather performing a large refactoring and retesting that cannot be justified because of a poorly named method, simply give it an alias that makes sense. That way new code will read properly in the future.

i.e. A grid control is saved, and there is a method name IsReferenceSelectedSendEmail. The name implies that the method will identify if the user selected reference in the grid is SendEmail. What the method really does is iterate over all the references and identifies if any one of them is SendEmail.

Simple solution. Alias the method as AnyReferenceIsSendEmail so that future code will read properly: if ( AnyReferenceIsSendEmail() )...

Now, if we can just get a keyword "unless" to negate an if condition.

IMO

donvnielsen
  • 195
  • 1
  • 9
5

Actually function aliases are more of delegates in C# terminology (like function pointers in C++). Here is one:

public class Test
{
    public void Test()
    {
        B += A;
    }

    public void A()
    {
        ...
    }

    public Action B;
}

But you'll have to call this as B.Invoke() as it is parameterless. If it had one or more parameters, this wouldn't be a problem.

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
2

This works.

class Program
{
    delegate void B();
    static Test t = new Test();
    static B b = t.A;

    static void Main(string[] args)
    {
        b();
    }

}

class Test
{
    public void A()
    {
    }
}
Brian
  • 221
  • 2
  • 2
1

C# is object oriented language, so you cant create "alias for function". You can only manipulate with classes. As it was mentioned, you can extend class with extension method, you also can create derived class and create new method in it, which would call derived method:

    class Test
    {
        public void A()
        {
            MessageBox.Show("Function A");
        }
    }

    class Test2: Test
    {
        public void B()
        {
            A();
        }
    }

But if you desire to call B() on your initial class Test you have only one way - creation of extension method.

Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
1

Even though C# does not support method alias directly, Expression-bodied members provide a nice-looking solution:

interface Schema
{
    void Generate();
    void Regenerate();
}

class PgSchema : Schema
{
    public void Generate()
    {
        Console.WriteLine("Executing original method...");
    }
    public void Regenerate() => Generate();
}

var pgSchema = new PgSchema();
pgSchema.Generate();
pgSchema.Regenerate();
// Prints "Executing original method..." two times.
Artur INTECH
  • 6,024
  • 2
  • 37
  • 34
0

There have been several comments on this post as to why someone would ever want to do this. I am currently implementing a Vector type for a graphics project, and the requirements document I am using refers to the Magnitude/Length of a Vector interchangeably. For the sake of efficiency, I'd rather not wrap a Magnitude() method inside of a Length() method, but it seemed like it would be nice for the sake of readability if the structure understood both terms.

The delegate method referred to by Christian Davén is probably the most efficient way to do this that I can see, but it is probably best to simply add documentation to the block of your method:

/// <summary>
/// Calculate the magnitude / length of a vector, including the W component.
/// </summary>
/// <remarks>
/// This calculation will break down if you try to take the magnitude of a point.
/// </remarks>
/// <returns>The magnitude / length of the vector.</returns>
public float Magnitude()
{
    return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
Trey Tomes
  • 76
  • 9
0

I know this is old but I do think its a relevant question and could have be addressed quite easily using delegates/Lambda expressions which were available in C# 3.0, which if memory serves me correct was around at the time of the OP.

Lets imagine we are creating a game that requires us to be signed into xbox live and have two buttons - one for signing in and one for switching user. A single function called SignIn will handle them both but this leads to poor readability when adding the onclick handler.

Fortunately this could be easily fixed using delegates and Lambda expressions.

Heres the SignIn function:

public static async void SignIn(object coreDispatcher)
{
...
}

Here is the Lambda Expression that creates the "alias"

public static async void SwitchUser(object param) => SignIn(param);

Now I can call either SignIn or SwitchUser and use the same code but provide more meaningful code

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • First of all welcome to StackOverflow. Your `SignIn` and `SwitchUser` samples are using a lot of language features that were introduced way later than C# 3 (for example: async, expression bodied members). Please align your sample code. – Peter Csala Aug 07 '20 at 09:24