C# version of remove_reference<T>?

Viewed 262

Is there an equivalent of C++'s std::remove_reference<T> in C#?

I have a String and String&, and in my project right now these should be considered equivalent.

In C++ I'd do something like is_same<T1, remove_reference<T2>::type>::value, but in C# I cannot figure out any good way to compare these types. The best I've come up with (and it's horrible) is:

if (
       0 == String.Compare(type1.Name, type2.Name + "&")
    || 0 == String.Compare(type1.Name + "&", type2.Name)
)

I've tried Type.IsAssignableFrom, and looking through all the various properties, but nothing has seemed to work so far.

2 Answers

I think what you're looking for is:

if (type2.IsByRef && type2.GetElementType() == type1)

See the GetElementType() and IsByRef documentation for details.

Note that the IsByRef part is required to avoid this being true for string[] as well as string& for example.

You can call GetElementType on the Type object for string&, and it will return the type object for string.

Related