Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with string as reference parameter when method takes Object C# [duplicate]

Possible Duplicate:
C# : Why doesn't 'ref' and 'out' support polymorphism?

I can't seem to understand why the following does not work in C#:

public static void Swap(ref Object a, ref Object b) {
    Object t = b;
    b = a;
    a = t;
}

//Calls
String fname = "Ford";
Strinf lname = "James";
Swap(ref lname, ref fname);

Is this because String already references to a char array, its immutable?

like image 537
James Ford Avatar asked Dec 10 '22 10:12

James Ford


1 Answers

This is a duplicate of

Why doesn't 'ref' and 'out' support polymorphism?

See that answer for why it doesn't work.

To make it work, you could make a generic method:

public static void Swap<T>(ref T a, ref T b) 
{
    T t = b;     
    b = a;     
    a = t; 
}

And now all the types check out.

like image 136
Eric Lippert Avatar answered Jan 25 '23 23:01

Eric Lippert