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();
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();
You can use an extension method
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.
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:
But if you desire to call
B()
on your initial classTest
you have only one way - creation of extension method.This works.
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
I'm surprised that noone has mentionedDelegates. It's probably as close to a method alias as you will come in C#:Actually function aliases are more of delegates in C# terminology (like function pointers in C++). Here is one:
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.