10

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

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
mat
  • 101
  • 1
  • 3
  • Properties and indexers are introduced for the convenience to use them as if they were values (even if under the hood they are multiple methods), but this is one of the reasons I don't like them. At least, there should have been some way of making what you want to do work, but currently, most of the new languages suck at that point. – comco Dec 15 '13 at 22:31

2 Answers2

2

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.

Craig Suchanec
  • 10,474
  • 3
  • 31
  • 39
0

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);
jCoder
  • 2,289
  • 23
  • 22
  • yeah I know, but it feels like a hack. :( Thanks. – mat Apr 16 '11 at 14:48
  • 1
    Based on information from MSDN it looks like that arrays in C# are not some kind of structure using pointers (also such things exist in unsafe context) but arrays are derived from System.Array so there is no "fast/direct access". To make your code cleaner you could wrap that code into an extension method which makes it more readable. – jCoder Apr 16 '11 at 15:21