Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension or Static Function?

I'm developing a middle sized project, where performans is really important. I could not find (actually can not understand) the difference between static and extension functions.

e.g:

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 same only extension function is called over its instance:

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

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

Thanks !

like image 843
icaptan Avatar asked Dec 01 '22 01:12

icaptan


2 Answers

There will be no difference in performance - a call to the extension method of

var result = foo.MyTransform(rotation);

will simply be converted by the compiler into:

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

Now that's not to say that extension methods should be used everywhere - but it looks like this is an appropriate use case, unless you could actually make it an instance method on Rotation:

var result = rotation.Apply(foo);

(As an aside, I'd strongly urge you to reconsider your names, in order to follow .NET naming conventions.)

like image 57
Jon Skeet Avatar answered Dec 04 '22 10:12

Jon Skeet


Extension methods ARE static methods. They are just syntactic sugar. The compiler will create a normal call to the static method. This means, they are equivalent.

like image 40
Daniel Hilgarth Avatar answered Dec 04 '22 11:12

Daniel Hilgarth