Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 267
mat Avatar asked Apr 16 '11 12:04

mat


1 Answers

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.

like image 54
Craig Suchanec Avatar answered Oct 13 '22 18:10

Craig Suchanec