Search code examples
c#system.reflection

How to get the Namespace of static void main() using Reflection?


I want to get the namespace of static void main() of the application from a library.

I know that you can use Reflection to get the entry assembly. Is there a method or a way in which I can get the namespace of the static void main() method?


Solution

  • This should give you the namespace of the class where the Main method of your executable is defined:

    Assembly.GetEntryAssembly().EntryPoint.DeclaringType.Namespace;
    

    Assembly.GetEntryAssembly gets you the assembly where the entry point is defined, the EntryPoint property gives you a MethodInfo that represents the Main method itself. You can then get the namespace from the Type returned from the DeclaringType property.