Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically created class to cs file?

I am creating a complex class with AssemblyBuilder that Im later creating objects from. There is however uncertainties in how this class is really contructed. So is there any way to write this dynamicly created class to a cs file for inspection?

I can get the dll file written to disk but I need the cs file.

like image 378
Banshee Avatar asked Sep 14 '18 09:09

Banshee


People also ask

Can we create a class dynamically in C#?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.

How do you create a dynamic class?

Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.

What is dynamic class in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.

Is it good to use dynamic type in C#?

It is definitely a bad idea to use dynamic in all cases where it can be used. This is because your programs will lose the benefits of compile-time checking and they will also be much slower.


2 Answers

You can decompile managed .NET dll to C# code using

  • DotPeek by JetBrains (free, sources are closed)
  • ILSpy open source project (MIT license sources are available at github)
  • Reflector by Red Gates (Paid tool, sources are closed)
  • JustDecompile by Telerik (free with open source decompilation engine available at github Apache License)
  • There is also a Microsoft's ildasm tool.

If you need to write custom tool you can download open-source code and give it a try.

like image 140
Access Denied Avatar answered Sep 29 '22 07:09

Access Denied


Do you have a requirement to use AssemblyBuilder? I'm asking because AssemblyBuilder wont allow you to see the generated class without using a decompiler and if the class you´re generating is quite complicated, the decompiled code wont be of good quality.
You are almost in the same situation if you use Reflection.Emit because it generates low level IL.
If you really need to see the source code that you're generating dynamically your best option is CodeDom. Here's an example How to: Create a Class Using CodeDOM

like image 26
emmanuel Avatar answered Sep 29 '22 06:09

emmanuel