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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With