Meitaim.Decompiler
1.1.0
Prefix Reserved
dotnet add package Meitaim.Decompiler --version 1.1.0
NuGet\Install-Package Meitaim.Decompiler -Version 1.1.0
<PackageReference Include="Meitaim.Decompiler" Version="1.1.0" />
<PackageVersion Include="Meitaim.Decompiler" Version="1.1.0" />
<PackageReference Include="Meitaim.Decompiler" />
paket add Meitaim.Decompiler --version 1.1.0
#r "nuget: Meitaim.Decompiler, 1.1.0"
#:package Meitaim.Decompiler@1.1.0
#addin nuget:?package=Meitaim.Decompiler&version=1.1.0
#tool nuget:?package=Meitaim.Decompiler&version=1.1.0
Meitaim.Decompiler
Decompiles .NET assemblies to C#. It reads them with System.Reflection.Metadata.
dotnet add package Meitaim.Decompiler
For the command line tool, see Meitaim.Decompiler.Tool.
Decompile an assembly
using Meitaim.Decompiler;
using var decompiler = AssemblyDecompiler.Open("Some.dll");
var code = decompiler.DecompileAssembly();
To write a large assembly straight to a file, pass a TextWriter:
using var file = File.CreateText("Some.cs");
decompiler.DecompileAssembly(file);
Decompile one type or method
To find a type by name, you need the assembly's metadata. Open the file as an AssemblyImage and read its Metadata:
using System.Reflection.Metadata;
using Meitaim.Decompiler;
using Meitaim.Decompiler.Metadata;
using var image = AssemblyImage.Open("Some.dll");
using var resolver = DirectoryAssemblyResolver.ForAssembly(image.FilePath);
using var decompiler = AssemblyDecompiler.For(image, resolver: resolver);
var metadata = image.Metadata;
var program = decompiler.TopLevelTypes()
.First(type => metadata.GetString(metadata.GetTypeDefinition(type).Name) == "Program");
var main = metadata.GetTypeDefinition(program).GetMethods()
.First(method => metadata.GetString(metadata.GetMethodDefinition(method).Name) == "Main");
var typeCode = decompiler.DecompileType(program);
var methodCode = decompiler.DecompileMethod(main);
Find where each member is in the text
DecompileTypeWithMemberSpans returns the text with the place of each member in it:
var decompiled = decompiler.DecompileTypeWithMemberSpans(program);
foreach (var span in decompiled.Members)
{
var memberCode = decompiled.Text.AsSpan(span.Start, span.Length);
}
Each span says which member it is, where its text starts, and how long the text is. Use it, for example, to show or highlight one member of a type that you decompiled once.
Find referenced assemblies
The decompiler reads referenced assemblies to spell names, operators and overrides correctly. Open looks for them in the directory of the assembly, then in the .NET runtime that runs your code. For without a resolver looks only in the runtime.
To search more directories, use DirectoryAssemblyResolver.ForAssembly. It takes the assembly's path so that it can search the assembly's directory first, like Open:
using var resolver = DirectoryAssemblyResolver.ForAssembly("Plugin.dll", "Game/Managed", "libs");
using var decompiler = AssemblyDecompiler.Open("Plugin.dll", resolver: resolver);
This looks in the directory of Plugin.dll, then Game/Managed, then libs, then the runtime. To search only the directories that you name, use new DirectoryAssemblyResolver("Game/Managed", "libs").
References are found by name, and the first file with that name wins, whatever its version. For a .NET Framework, Mono or Unity assembly, add the directory that holds its references, because your code runs on a newer .NET.
To resolve from somewhere else, such as assemblies in memory, implement IAssemblyResolver. Return null for an assembly you cannot find:
sealed class InMemoryResolver(IReadOnlyDictionary<string, AssemblyImage> images) : IAssemblyResolver
{
public ResolvedAssembly? Resolve(AssemblyIdentity reference) =>
images.TryGetValue(reference.Name, out var image) ? ResolvedAssembly.Of(image) : null;
}
AssemblyImage.FromImage opens an assembly from its bytes.
Decompile many assemblies that share references
SharedReferences reads each referenced assembly once for all the decompilers that use it, also on several threads at once:
using var resolver = new DirectoryAssemblyResolver("Game/Managed");
var references = new SharedReferences(resolver);
foreach (var path in Directory.EnumerateFiles("Game/Managed", "*.dll"))
{
using var image = AssemblyImage.Open(path);
using var decompiler = AssemblyDecompiler.For(image, references);
using var file = File.CreateText(Path.Combine("decompiled", Path.GetFileNameWithoutExtension(path) + ".cs"));
decompiler.DecompileAssembly(file);
}
Change the output
DecompilerOptions is a record, so change the defaults with with:
var options = DecompilerOptions.Default with
{
IndentUnit = "\t",
NewLine = "\r\n",
UseFileScopedNamespaces = false,
UsePrimitiveKeywords = false,
IncludeMethodBodies = false,
LanguageVersion = CSharpLanguageVersion.Preview,
ImplicitNamespaces = [],
MaxDegreeOfParallelism = 1,
};
using var decompiler = AssemblyDecompiler.Open("Some.dll", options);
ImplicitNamespaces are the namespaces that the output does not import, because a project imports them already. The default is the list that <ImplicitUsings> imports in a console project. Set it to [] to get a using for each namespace that the code needs.
CSharpLanguageVersion.Latest writes C# that compiles with the newest released C#. Preview writes C# that needs <LangVersion>preview</LangVersion>.
MaxDegreeOfParallelism is how many types of one assembly the decompiler writes at once. The default is one for each processor.
Check what the decompiler could not resolve
Diagnostics.All lists the places where the C# may not match the IL:
var code = decompiler.DecompileAssembly();
foreach (var diagnostic in decompiler.Diagnostics.All)
{
if (diagnostic is MethodDiagnostic inMethod)
{
Console.Error.WriteLine($"{diagnostic.GetType().Name}: {inMethod.Count} in {inMethod.MethodSignature}");
}
}
The type of each entry names its kind. Count is how many times the kind occurs at that place. Every kind except UnspelledAssemblyAttributes is a MethodDiagnostic: Method is the handle of the method in the decompiled assembly, and MethodName is its name after its namespace and the types that contain it, such as Shapes.Grid.Cell..ctor. MethodSignature adds the type parameters of the method and of the types that contain it, and the parameter types, such as Shapes.Grid<T>.Copy(int, Span<byte>), so that it tells overloads apart. A conversion operator starts with its return type, such as decimal Shapes.Money.op_Implicit(Money). A method that takes __arglist ends with it. It spells the types as the decompiler does with the default options. A lambda, a local function or a state machine that the output writes inside its method counts toward that method. One that the output keeps as a member of its own, such as Sample.<Walk>g__Step|0_0, or a state machine type that you decompile by itself, counts under its own metadata name. The list has no set order.
| Kind | What the output has | Details |
|---|---|---|
GuessedOperatorSpellings |
An operator whose name the decompiler guessed, because the interface that declares it was not found. | OperatorName, such as op_Addition. Count is always 1. |
DroppedInterfaceImplementations |
A method that implements more interface members than C# can declare on one method. The others are left out. | Count is how many it left out. |
UnfixedPinnedLocals |
A pinned local that did not become a fixed statement. |
|
UnjoinedSpills |
A temporary variable for a value that the IL keeps on the stack across branches. | |
ConstructorChainStatements |
A base(...) or this(...) call left as a statement in the constructor body. |
|
BoxedExplicitCallReceivers |
A cast of a struct to an interface, added to call its explicit implementation. The cast boxes the struct, so the call changes a copy. | |
HiddenSlotCalls |
A direct call to a method that neither base. nor this. reaches in C#, so the C# may call another implementation. |
|
UnspelledAssemblyAttributes |
An #error line where no C# attribute can write an assembly attribute. |
Target is AttributeTargets.Assembly or AttributeTargets.Module. Attribute is the text after the target on the #error line. Count is always 1. |
TakeAll returns the entries and removes them, so that each entry reaches one caller even while other threads report more. After TakeAll, All and the obsolete counters show only the entries reported since.
The counters from version 1.0, such as ConstructorChainsLeftAsStatements and ConstructorChainSites, still work but are obsolete. Each one adds up the Count of one kind in All.
Things to know
Opencloses the file when you dispose the decompiler.Fordoes not dispose the image or the resolver that you give it.TopLevelTypesleaves out nested types. They are written inside the type that contains them.- The output leaves out a
usingfor each namespace inImplicitNamespaces. With the default list, it compiles in a project with<ImplicitUsings>turned on. - The output ends lines with
\non every operating system, unless you setNewLine. Diagnosticscollects over every call on the same decompiler. To check one type alone, callDiagnostics.TakeAll()after you decompile it.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- No dependencies.
-
net11.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Highlight: `dotnet decompile --project` writes a .csproj next to the C#, so the output builds with the right references, extern aliases and target framework.
Features:
- `--project` writes a .csproj for each assembly. Types forwarded into another assembly that clash with direct references now get extern aliases too.
- `Diagnostics.All` and `Diagnostics.TakeAll()` list each diagnostic with the method it occurs in and how many times. The 1.0.0 counters still work but are obsolete.
- The library and the tool each have their own README.
Fixes:
- Extern aliases now parse inside interpolated strings, and aliases named like a keyword or `global` compile.
- Anonymous delegates are written as source writes them, so they no longer fail with CS1908.
- Lambdas keep their parameter defaults and `params` arrays.
- Parameter and return attributes, and attributes stored as metadata flags (`MethodImpl`, `Serializable`, `NonSerialized`, `ComImport`, `SpecialName`, `Optional`, `AssemblyVersion`), are written.
- `const decimal` fields and decimal parameter defaults come back, so they're no longer `static readonly` or missing.
- `DefaultMember` stays on types without an indexer, and indexers not named `Item` keep their name through `IndexerName`.
Performance:
- The native tool uses a fresh PGO profile, recorded for each platform.