Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Disclaimer</strong><br> Let me start out by saying that the method I'm going to demonstrate here is purely for educational purposes. Please use the switch or dictionary lookups demonstrated in the other answers in your production code.</p> <p><strong>Answer</strong><br> So, the only way to find out how the compiler would interpret a given piece of code is to actually compile it and inspect the generated assembly. This isn't so hard to do in .NET... You could compile an arbitrary string during runtime using the C# compiler like so:</p> <pre><code>private static Type GetTypeByFullNameOrAlias(string typeName) { Type type = Type.GetType(typeName); if (type == null) { using (var provider = new CSharpCodeProvider()) { var compiler = provider.CompileAssemblyFromSource( new CompilerParameters {GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false}, "public class A { public " + typeName + " B; }"); type = ((FieldInfo)compiler.CompiledAssembly.GetType("A").GetMember("B")[0]).FieldType; } } return type; } </code></pre> <p>However, this technique has several drawbacks... First of all it is slow. Of course you could cache the result and do other trickery to speed up the process. But there's another problem, which is that it compiles and loads a complete assembly each time it reaches the inside of the "if" statement. Each assembly it loads cannot be unloaded again and will hang around until the application closes, so this technique will also leak a small amount of memory. Again, you could load the generated assembly into an separate AppDomain and unload the domain after you've inspected the type but that would only make the code a lot slower.</p> <p>But as I pleaded in the beginning, just use the "switch" solution in your production code... It does a perfectly good job of translating the aliases. And it's not like they're going to change those language aliases anytime soon.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload