Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Type.IsByRef for type String return false if String is a reference type?

Tags:

c#

.net

According to this a string (or String) is a reference type.

Yet given:

Type t = typeof(string);

then

if (t.IsByRef) ...    

returns false

why?

Edit: After some quick testing, I'm obviously misunderstanding the purpose of IsByRef... as even using a class name in place of 'string' ,returns false as well. I'm writing a generic class and want to test if one the types passed in when the generic is instantiate is a value or reference type. How does one test for this?

like image 255
PMBottas Avatar asked May 16 '13 03:05

PMBottas


People also ask

Is String a value type or a reference type?

String is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. If we change a string value, then the compiler creates a new string object in the memory and point a variable to the new memory location.

Why is int value type and String reference type?

The data type Integer is a value type, but a String is a reference type. Why? A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.

What is the type of a String class A value type B reference type?

It's a reference type.


2 Answers

There are "reference types" -- for which we have !type.IsValueType -- and then there are types that represent references to anything -- whether their targets are value types or reference types.

When you say void Foo(ref int x), the x is said to be "passed by reference", hence ByRef.
Under the hood, x is a reference of the type ref int, which would correspond to typeof(int).MakeReferenceType().

Notice that these are two different kinds of "reference"s, completely orthogonal to each other.

(In fact, there's a third kind of "reference", System.TypedReference, which is just a struct.
There's also a fourth type of reference, the kind that every C programmer knows -- the pointer, T*.)

like image 174
user541686 Avatar answered Sep 23 '22 16:09

user541686


You should use IsValueType instead:

bool f = !typeof (string).IsValueType; //return true;

As for IsByRef, the purpose of this property is to determine whether the parameter is passed into method by ref or by value.

Example you have a method which a is passed by ref:

public static void Foo(ref int a)
{
}

You can determine whether a is pass by reference or not:

  bool f = typeof (Program).GetMethod("Foo")
                                 .GetParameters()
                                 .First()
                                 .ParameterType
                                 .IsByRef;   //return true
like image 35
cuongle Avatar answered Sep 26 '22 16:09

cuongle