1

My code is littered with

someInt=0;

I keep constantly "resetting" my integers.

Would it be possible to implement an extension method that will set the integer to 0?

Something like this:

public static void Reset(this int num) =>num=0;

And the intended usage would be:

someInt.Reset;

However that will not work, since integer is a value type.

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

2 Answers2

2

You could use a struct as a struct is a value type, i.e.

public struct IntegerHolder
{
    public int val;

    public reset() {
        myInt = 0
    }
}
public void main()
{
    IntegerHolder MyInteger
    MyInteger.val = 5 //Set the val to 5
    MyInteger.reset() //Reset it back to 0
}

But it is probably more efficient to use int = 0 instead. just offering a usable solution

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Byren Higgin
  • 552
  • 4
  • 13
1

See Impossible to use ref and out for first ("this") parameter in Extension methods? - you would need to use ref or out as an option for the parameter, but they're mutually-exclusive with the this modifier.

I don't think you have a good idea - because the code foo = 0; is succint and immediately obvious what it does - wrapping it in an extension method is pointless because it doesn't solve any problems, it adds complexity, and adds the potential for bugs (what if one user of Reset needs to reset to 1 instead of 0 and blindly changes the definition of Reset? It would break the rest of your code.

Don't use a language feature just because it's there - a good programmer knows when to not use a language feature.

If you really do want to add functionality like this, use something like T4 or make a template extension for Roslyn.

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374