Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the opposite of Type.MakeByRefType

The Type.MakeByRefType method in .NET returns a by-ref version of a type, e.g. passing the type of System.Int32 returns a type representing System.Int32&.

However, if you already have a System.Int32&, what is the mechanism for obtaining a plain old System.Int32? There doesn't seem to be an opposite method to remove the by-ref modifier.

At the moment I've put a hack in place which re-builds the assembly-qualified name without an & at the end of the type name and then loads that type, but this is horribly dirty...

like image 920
Greg Beech Avatar asked Mar 03 '09 16:03

Greg Beech


1 Answers

According to the docs for IsByRef, you can use Type.GetElementType.

This is also true for types for which IsArray or IsPointer is true.

var typeInt = typeof(int);
var typeIntRef = typeInt.MakeByRefType();
var typeIntArray = typeInt.MakeArrayType();
var typeIntPointer = typeInt.MakePointerType();

Debug.Assert(typeIntRef.GetElementType() == typeInt);
Debug.Assert(typeIntArray.GetElementType() == typeInt);
Debug.Assert(typeIntPointer.GetElementType() == typeInt);
like image 131
Jon Skeet Avatar answered Oct 24 '22 08:10

Jon Skeet