How do I access 'this' from a C # extension method?

I've worked with Vector2 and XNA, and I've come to the conclusion that calling the Normalize () function on a null vector will normalize it to the vector {NaN, NaN}. This is all well and good, but in my case, I would rather just leave them as null vectors instead.

Adding this code to my project involved a cute extension method:

using ExtensionMethods;

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static Vector2 NormalizeOrZero(this Vector2 v2)
        {
            if (v2 != Vector2.Zero)
                v2.Normalize();
            return v2;
        }
    }
}

      

Unfortunately, this method returns a normalized vector, not just normalizes the vector that I am using to call this extension method. I would like to behave like vector2Instance.Normalize () instead.

Besides creating this void, how do I set it up so that "v2" is modified? (Basically, I need access to the 'this' object, or I need "v2" to be passed by reference.)

Edit:

And yes, I tried this:

    public static void NormalizeOrZero(this Vector2 v2)
    {
        if (v2 != Vector2.Zero)
            v2.Normalize();
    }

      

Doesn't work, v2 is just a variable in the NormalizeOrZero scope.

+1


source to share


4 answers


This doesn't work because Vector 2 is actually a structure . This means it is passed by value and you cannot modify the caller copy. I think the best you can do is the workaround given by lomaxxx.



This illustrates why you should avoid using structs altogether. See this question for more information. Vector2 violates the directive that structs must be immutable, but it probably makes sense to do it in the XNA context.

+3


source


Well, if you really just know how to do this, you can do something like this:

public static void NormalizeOrZero(this Vector2 ignore, ref Vector2 v2)
{
    if (v2 != Vector2.Zero)
        v2.Normalize();
}

      

You would call it like this:



v2.NormalizeOrZero(ref v2);

      

It might sound ugly, but it will work, for what it's worth. But at this point, you can also call the static method in the first place.

+1


source


I'm not sure why your second code sample doesn't work, but if the first piece of code does what you want, you can simply work around it by going:

Vector2 v2 = new Vector2()
v2 = v2.NormalizeOrZero();

      

0


source


You will need the ref

and modifier in the argument this

, which is unlikely to work.

0


source







All Articles