7

Given a .NET type object found through reflection, is it possible to pretty print or decompile this type as a C# declaration, taking into account C# type aliases, etc.?

For example,

Int32 -> int
String -> string   
Nullable<Int32> -> int?
List<au.net.ExampleObject> -> List<ExampleObject>

I want to be able to print out methods close to what was originally written in the source.

If there isn't anything in the .NET framework, is there a third-party library? I might possibly have a look at ILSpy.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick Sonneveld
  • 3,356
  • 6
  • 39
  • 48

4 Answers4

9

See this answer.

Example:

using System.CodeDom;
using System.CodeDom.Compiler;

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

var typeRef = new CodeTypeReference("System.Nullable`1[System.Int32]");
string typeOutput = provider.GetTypeOutput(typeRef); // "System.Nullable<int>"

It will help you with int and string-like things, as well as generics, however you'll have to work out Nullable<T> -> T? and usings yourself.

Community
  • 1
  • 1
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
1

Aliases are compiled to what they are an alias for. You will never know if it was string or String in the source and frankly I can't see why it would matter.

Jonas Elfström
  • 30,834
  • 6
  • 70
  • 106
1

There are only 15 aliases (+Nullable). Just use string.Replace on these.

Community
  • 1
  • 1
adrianm
  • 14,468
  • 5
  • 55
  • 102
0

There is a solution for type declarations in another post . You can extend it to support type aliases easily.

Community
  • 1
  • 1
George Polevoy
  • 7,450
  • 3
  • 36
  • 61
  • Yeah, that's why I considered looking at the source of a c# decompiler. Actually, Jon Skeet has mentioned CSharpCodeProvider in another question. – Nick Sonneveld Jun 07 '11 at 09:31