Extension or static function?

I am developing a medium-sized project where the performers are really important. I could not find (actually can not understand) the difference between static and extension functions.

eg:

public static class My { public static Vector2 MyTransform(this Vector2 point, float Rotation) { //.... return MyVector; } public static Vector2 MyTransform(Vector2 point, float Rotation) { //.... return MyVector; } } 

These functions are used in the same way as for its instance; it calls only the extension function:

  • Vector2 calc = myVector.MyTransform (0.45f);
  • Vector2 calc = My.MyTransform (myVector, 0.45f)

Which one do you prefer to use, or do you prefer to use and why?

Thanks!

+4
source share
4 answers

There will be no difference in performance - calling the extension method

 var result = foo.MyTransform(rotation); 

will be simply converted by the compiler to:

 var result = My.MyTransform(foo, rotation); 

Now, not to say that extension methods should be used everywhere, but it looks like this is a suitable use case, unless you could make it an instance method when rotating:

 var result = rotation.Apply(foo); 

(As an aside, I urge you to redefine your names to follow the .NET naming conventions.)

+9
source

ARE extension methods are static methods. This is just syntactic sugar. The compiler will create a regular call to the static method. This means that they are equivalent.

+5
source

Two functions are implemented in exactly the same way. Logically, however, extension methods allow you to provide common functionality for multiple interfaces , so this is more than just syntactic sugar.

+3
source

They are called "extension methods" and are not expanded.

An extension method is just a convenient way to make it look as if it were part of an object definition.

If you write:

 public static void DoSomething(this MyObject myObject) { } 

This means that you can call it like this: from an instance of MyObject :

 myObject.DoSomething(); 

If you omit the this in a method definition, you cannot invoke it this way, but only like this:

 DoSomething(myObject); 

Please note that although the first call is possible only if you write the method as an extension method (with the this ), the latter is possible in both cases.

+2
source

Source: https://habr.com/ru/post/1386332/


All Articles