decompiler-nuget-demos.ipynb
You must install .NET Interactive Notebooks extension in VS Code to run this notebook!
Load the NuGet package and print out the version to make sure we are using the latest and greatest
#r "nuget: ICSharpCode.Decompiler, 8.1.0.7455"
using System.Reflection.Metadata;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
Console.WriteLine(typeof(FullTypeName).Assembly.GetName());
You must have compiled ILSpy.XPlat.slnf first (run “dotnet build” in ICSharpCode.Decompiler.PowerShell folder). Make sure to modify basePath to your repository path.
const string basePath = @"D:\GitWorkspace\ILSpy\";
string testAssemblyPath = basePath + @"ICSharpCode.Decompiler.PowerShell\bin\Release\netstandard2.0\ICSharpCode.Decompiler.dll";
var decompiler = new CSharpDecompiler(testAssemblyPath, new DecompilerSettings());
Get the count of types in this module
var types = decompiler.TypeSystem.MainModule.TypeDefinitions;
Console.WriteLine(types.Count());
Decompile a known type (as a whole)
// ICSharpCode.Decompiler.Util.Empty<T> -> translates to `n, where n is the # of generic parameters
var nameOfGenericType = new FullTypeName("ICSharpCode.Decompiler.Util.Empty`1");
Console.WriteLine(decompiler.DecompileTypeAsString(nameOfGenericType));
If you want to decompile one single member (sample: first method)
var nameOfUniResolver = new FullTypeName("ICSharpCode.Decompiler.Metadata.UniversalAssemblyResolver");
ITypeDefinition typeInfo = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
var tokenOfFirstMethod = typeInfo.Methods.First().MetadataToken;
Console.WriteLine(decompiler.DecompileAsString(tokenOfFirstMethod));
If you need access to low-level metadata tables
ITypeDefinition type = decompiler.TypeSystem.FindType(nameOfUniResolver).GetDefinition();
var module = type.ParentModule.PEFile;
Get the child namespaces
var icsdns = decompiler.TypeSystem.RootNamespace;
foreach (var cn in icsdns.ChildNamespaces) Console.WriteLine(cn.FullName);
Get types in a single namespace
var typesInNamespace = icsdns.ChildNamespaces.First(cn => cn.FullName == "LightJson").Types;
Console.WriteLine(typesInNamespace.First().FullTypeName);