Problem with a string as a reference parameter when a method accepts a C # object

Possible duplicate:
C #: Why is 'ref' and 'out' polymorphism not supported?

I cannot 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 it because String already refers to the char array, is it immutable?

+4
source share
3 answers

This is a duplicate

Why is polymorphism "ref" and "out" not supported?

Look at this answer why it does not work.

To do this, you can make a general method:

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

And now all types are checked.

+9
source

Once again I need to refer to Eric Lippert's blog post (second time today!) On this topic:

Why don't the ref and out parameters allow me to change the type?

Basically, this conversion will violate type safety, because you can change the reference to an object to store another type that does not match the type passed to the callers.

Neither ref nor out parameters can be distinguished by type on the call site. Do otherwise - break the security type being checked.

+3
source

It is impossible to compile, and fortunately. Imagine you put an integer in an a or b object in a swap method. This would not be possible at all, because the actual reference refers to a type string object.

You can disable this behavior in a dynamically typed scripting language, such as JavaScript or PHP, because it is just "var" anyway. But in a statically typed language like C #, this is not possible.

+2
source

Source: https://habr.com/ru/post/1343560/


All Articles