damocles
damocles

Reputation: 173

accessing the variable of an extension method (C#)

Is it possible to modify the this/focus variable in a static extension method?

For example:

public static class AnimExtensions
{
    public static int anim(this float f, float to, float time)
    {
        return Animation.Start(a => f = a, f, to, time);
    }
}

I would like to call the Animation.Start method using an extension to float, by using the lambda function on the 'this' variable. The this keyword is not allowed in extension methods, but is there another way to access/use the variable in this fashion?

Upvotes: 1

Views: 449

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

I'm not sure what you're asking. What's the type of the first argument of the Animation.Start method?

The type float (System.Single) is immutable so you can't modify the f object. You can assign f to a new object (saying e.g. f = 3.14F; or f++;) but as Jon Skeet explains in his answer, that's useless (ref/out can't combine with this).

If you make an extension method on a mutable reference type, say List<>, then it's possible to modify the "this" object, as in:

public static void AbsAll(this List<float> list)
{
  for (int i = 0; i < list.Count; ++i)
    list[i] = Math.Abs(list[i]);
}

It still won't be useful to assign list to a new object, of course.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

You can certainly modify the parameter - but it won't have any effect, as the argument is passed by value as per normal methods.

You can't declare the first parameter of an extension method to be ref or out, which is what would be required for it to have an effect.

Upvotes: 8

Related Questions