C# Method to Get the Full Name of a Namespace

How to Get the Full Name of a Namespace as a String in C#, dotnet,csharp,reflection,namespace

In this post, I'm sharing a dotnet/c# code to get the full name of a namespace and convert it to a string.

Assuming we have a class called "Order" and we need to get its namespace as a string. Here are few options on how to do it in c#:

Option 1

var classType = typeof(OrderClass);
var n = classType.Namespace;
Console.WriteLine("Namespace: {0}.", n);

Option 2

You can create a method in class "Order" to return its namespace. You can add this method to a base class so you don't have to repeat the same code in all classes.

public string GetClassNamespace()
{
   return GetType().Namespace;
}

Option 3

You can make use of the keyword "nameof", which is available in C#6 and above. A nameof expression produces the name of a variable, type, or member as the string constant. 

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic

Do you have a better way to get the full name of a namespace? Please share it with us in the comments.


Post a Comment

Previous Post Next Post