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?
You want to check if it is a value type.
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)
, thex
is said to be "passed by reference", henceByRef
.Under the hood,
x
is a reference of the typeref int
, which would correspond totypeof(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 astruct
.There's also a fourth type of reference, the kind that every C programmer knows -- the pointer,
T*
.)You should use
IsValueType
instead: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:You can determine whether
a
is pass by reference or not: