Reputation: 1460
Hi I have a simple enum Service on which there are few extension methods defined
public enum Service
{
//enum values ..
}
public static class ServiceExtensions
{
internal static string GetSomeCode(this Service service)
{
// Does something
}
//another extension method that calls GetSomeCode()
internal static string GetSomeOtherData(this Service service)
{
// Look at the call for extension method here
string code = GetSomeCode(service);
}
}
I know that the syntax for calling extension method is similar as calling for member function for this
specified type.
In above example it should be as -
string code = service.GetSomeCode();
I found similar use of syntax at other places in the project. I my question is there any difference between both the calls. If not then which should I prefer using ?
Upvotes: 2
Views: 602
Reputation: 22714
No, there is no difference. Further more the latter (service.GetSomeCode()
) will be converted to the former (GetSomeCode(service)
) during compilation.
If you visit sharplab.io and paste there the following code:
public enum Service
{
}
public static class ServiceExtensions
{
internal static string GetSomeCode(this Service service)
{
return "";
}
internal static string GetSomeOtherData(this Service service)
{
string code = service.GetSomeCode();
return code;
}
}
Then you will see that the decompiled code will look like this:
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: Extension]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public enum Service
{
}
[Extension]
public static class ServiceExtensions
{
[Extension]
internal static string GetSomeCode(Service service)
{
return "";
}
[Extension]
internal static string GetSomeOtherData(Service service)
{
return GetSomeCode(service);
}
}
So, it is just a syntactic sugar.
Upvotes: 4