I am writing a program which needs the namespace of the program but I cant seem to figure out how to retrieve it. I would like the end result to be in a string.
I was able to find an MSDN page about this topic but it proved to be unhelpful to myself. http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx
Any help would be appreciated. The program is written in C#.
EDIT: Sorry guys, this is not a console application.
The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. C# Copy.
A namespace can be included in a program using the using keyword.
You can't name a namespace starting with a number.
A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.
This should work:
var myType = typeof(MyClass);
var n = myType.Namespace;
Write out to the console:
Type myType = typeof(MyClass);
Console.WriteLine("Namespace: {0}.", myType.Namespace);
Setting a WinForm label:
Type myType = typeof(MyClass);
namespaceLabel.Text = myType.Namespace;
Or create a method in the relevant class and use anywhere:
public string GetThisNamespace()
{
return GetType().Namespace;
}
To add to all the answers.
Since C# 6.0 there is the nameof keyword.
string name = nameof(MyNamespace);
This has several advantages:
Note: This doesn't give the full namespace though. In this case, name
will be equal to Bar
:
namespace Foo.Bar
{
string name = nameof(Foo.Bar);
}
Put this to your assembly:
public static string GetCurrentNamespace()
{
return System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.Namespace;
}
Or if you want this method to be in a library used by your program, write it like this:
[System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentNamespace()
{
return System.Reflection.Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace;
}
This can't go wrong:
MethodBase.GetCurrentMethod().DeclaringType.Namespace
if you have item x
of class A
in namespace B
you can use:
string s = x.GetType().Namespace;
no s
contains "B"
you can also use x.GetType().Name
to get the type name or x.GetType().FullName
to get both
You could simply use typeof and then pass in the class (I.e. Program):
Console.WriteLine(typeof(Program).Namespace);
Which would print:
ConsoleApplication1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With