-1

anyone knows a way to solute this smart?

public static void Invert(this ref bool value)
{
    value = !value;
}

c# says i can not use "ref" or "out" within an extension. But such extensions like List.Clear() exist.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
fubo
  • 44,811
  • 17
  • 103
  • 137

2 Answers2

7

List.Clear() isn't an extension method, it's a method. And even if it was an extension method, it wouldn't need to receive the parameter as ref, because it doesn't "return" a different list than the one you had, it modifies the list.

And, in general, you can't. But you normally don't need to.

What about:

public static bool Invert(this bool value)
{
    return !value;
}

bool x = false.Invert();
xanatos
  • 109,618
  • 12
  • 197
  • 280
4

First of all, I know of no List.Clear extension method. List<T>.Clear() is a normal method. It has no ref parameters.

The second issue is that List<T> is a mutable reference type. So you can modify it, without changing the reference itself. You only need ref if you want to change the reference itself, or if you're working on a value type.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262