mat
mat

Reputation: 101

Generic Swap difficulty

I'm coming from C++ where it's easy to do something like this:

template<class T>
void Swap(T &a, T &b)
{
  T temp = a;
  a = b;
  b = temp;
}

and then use it to swap values in a container:

std::vector<int> someInts;
someInts.push_back(1);
someInts.push_back(2);

Swap(someInts[0], someInts[1]);

However, upon attempting to do the same thing in C#

void Swap<T>(ref T a, ref T b)
{
        T temp = a;
    a = b;
    b = temp;
}

I get the error "property or indexer may not be passed as an out or ref parameter"

Why is this and how can I overcome it?

Many thanks

Upvotes: 10

Views: 3458

Answers (2)

Craig Suchanec
Craig Suchanec

Reputation: 10804

You cannot use indexers or properties ref parameters. The reason is you are retuning a reference to the object but not the location so any effect the function would have would not actually change the source as it wouldn't write it back to the location (i.e. not call the setter in the case of a property). You need to pass the array into the method so that the method can set values an indexes as well as know what values to swap.

Upvotes: 2

jCoder
jCoder

Reputation: 2319

Properties and the indexer are actually methods (created by the compiler behind the scenes), so I suppose it is not possible to do call-by-reference on them. However you could write a method like this:

public void Swap<T>(T[] data, int a, int b) {
  T temp = data[a];
  data[a] = data[b];
  data[b] = temp;
}

Swap(someInts, 0, 1);

Upvotes: 0

Related Questions