1

I recently came across this (highly-voted) community wiki, which states

you can't use string in reflection; you must use String.

however, since the answer is from 2011 and since I have never experienced any issues with using string in reflection scenarios, I was wondering whether the statement still holds true.

Additionally, taking into account that both string and System.String get compiled to System.String and string being merely an alias for System.String, I don't think there are any potential differences, let alone problems.


I tried to find differences or problems when using string in reflection, but I couldn't find any:

Getting the Type:

string a = "Foo";
System.String b = "Foo";

Type aType = a.GetType(); // yields System.String - big surprise ;)
Type bType = a.GetType(); // yields System.String

Calling a method at runtime:

string a = "Foo Bar";
System.String b = "Foo Bar";

bool aContainsBar = (bool) a.GetType()
                            .GetMethod("Contains")
                            .Invoke(a, new object[] { "Bar" });
// yields true - big surprise again ;)

bool bContainsBar = (bool) b.GetType()
                            .GetMethod("Contains")
                            .Invoke(a, new object[] { "Bar" });
// also yields true

200+ votes don't lie - I am very interested in what differences between using string and System.String in reflection there are / were.

Is the statement still correct? If so, can you please provide me with an example showing the difference between string and System.String?

Thomas Flinkow
  • 3,956
  • 5
  • 23
  • 52
  • 3
    `string` is a language keyword, not an alias for the type. Reflection doesn't know anything about language keywords, it only knows about .NET types. – Panagiotis Kanavos May 11 '18 at 10:04
  • 5
    I think the point they were aiming for is - you cannot use `string` as the *name* of a type, when you e.g. try to use [`GetType`](https://msdn.microsoft.com/en-us/library/y0cd10tb(v=vs.110).aspx) or [`GetType`](https://msdn.microsoft.com/en-us/library/w3f99sx1(v=vs.110).aspx) – Damien_The_Unbeliever May 11 '18 at 10:05
  • 2
    No, I mean `Type.GetType("string")` returns `null`, whereas `Type.GetType("System.String")` returns a runtime type representation of the string class. The links in my previous comment are to `GetType` methods that accept a type name as a *parameter*. – Damien_The_Unbeliever May 11 '18 at 11:26

0 Answers0