-2

How do I get a class' source code inside a C# program?

class Foo {
    string void Bar(){
        return "baz";
    }
}

Then in another file:

GetSourceCode(Foo) // => class Foo { string void Bar() { return "baz": } }

I was told ILSpy could do it based on this question: Can Roslyn generate source code from an object instance?, but there is absolutely no new usage examples at all.

The code in that linked question is out of date. AssemblyDefinition, Assembly, CSharpLanguage and DecompilationOptions are all unavailable in the current context, despite using ICSharpCode.Decompiler, ICSharpCode.Decompiler.CSharp and ICSharpCode.Decompiler.TypeSystem;

https://github.com/icsharpcode/ILSpy

E_net4
  • 27,810
  • 13
  • 101
  • 139

1 Answers1

1

I have used dotPeek which is a free tool from JetBrains. Very good and simple to use. You will need the DLL's or the executable that you want to decompile

Helped me save an entire of folder that I rolled back by accident once

Narish
  • 607
  • 4
  • 18
  • Is it a libary that can be used in a C# project? Because it looks like an executable that can be used to decompile, that isn't quite what I want – CaptainDucko Jun 03 '22 at 16:53
  • No this is a program that will take a .dll or .exe and decompile its source code for you, which you can use afterward. Why exactly do you want this as a library in a project? If you need something of that sort you probably need to look into the [Reflection namespace](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection) but to be honest I can't say that for sure as I don't know what you want to do exactly – Narish Jun 03 '22 at 16:59
  • not what I want – CaptainDucko Jun 03 '22 at 17:08
  • @CaptainDucko maybe take a look at this [question](https://stackoverflow.com/questions/2693881/can-i-use-reflection-to-inspect-the-code-in-a-method) and its answer. I don't know what exactly you want to do with the generated code, but Reflection can emit the IL code which another library Cecil can then perform operations on. I have never done it myself, but I hope this helps – Narish Jun 03 '22 at 18:19
  • The .Net VM doesn't actually use your written code, it cares for the IL that is generated from the stepped down optimization of your code (all of which .net handles internally in the compilation process). In a sense, your dll's and executables don't know much of anything about the code you wrote yourself, it prefers the lower level IL. Only tools like dotPeek can reverse engineer written C# code from IL. So in essence your best bet may be this process of output the IL stream then get an external library to help you do what you intend – Narish Jun 03 '22 at 18:21