Whats the difference between matrix.Extension() and ExtensionMethods.Extension(matrix) ??
static void Main(string[] args)
{
decimal[,] testData = new[,] {{1m, 2m}, {3m, 4m}};
ImmutableMatice matrix = new ImmutableMatice(testData);
Console.WriteLine(matrix.Extension());
Console.WriteLine(ExtensionMethods.Extension(matrix)); // return the same like matrix.Extension() but whats the difference?
}
Extension class
static class ExtensionMethods
{
public static string Extension(this ImmutableMatice array)
{
Console.WriteLine("Values of array are: ");
for (int i = 0; i < array.Array.GetLength(0); i++)
{
for (int j = 0; j < array.Array.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", array[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
return null;
}
Whats the difference between matrix.Extension() and ExtensionMethods.Extension(matrix)?
Nothing whatsoever. The compiler translates the first into the second, effectively.
There will be a difference in C# 6, where if you've statically imported the ExtensionMethods
type specifically, the first will work and the second won't. From the "Upcoming features in C#" doc:
Extension methods are static methods, but are intended to be used as instance methods. Instead of bringing extension methods into the global scope, the using static feature makes the extension methods of the type available as extension methods
(This hasn't been implemented in the current CTP though.)
Given that they're equivalent, you may be asking yourself why this syntactic sugar exists at all. There are two reasons:
It makes it far more convenient to chain method calls together, if some of them happen to be static. For example:
foo.Bar().Baz().Qux()
is simpler to read than:
ThirdClass.Qux(SecondClass.Baz(FirstClass.Bar(foo)))
It allows for the LINQ pattern to work consistently across interfaces and types, whether the types implement the pattern directly as instance members, or whether extension methods are used.
See more on this question at Stackoverflow