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 wa
as a roll upp all post answers: getting all columns' values from a table given as a string tableName:
var tableName = "INVENTORY_PRICE"; var assembly = Assembly.GetExecutingAssembly(); var tip = typeof(Form3); var t = assembly.GetType(tip.Namespace + "." + tableName); if (t != null) { var foos = db.GetTable(t); foreach (var f in foos) { Console.WriteLine(f + ":"); foreach (var property in f.GetType().GetProperties()) if (property != null) { var pv = property.GetValue(f, null); Console.WriteLine(" " + property.Name + ":" + pv); } Console.WriteLine("------------------------------------------------"); } }
it is very easy if we use ado, this sample uses LINQ context...
Type myType = typeof(MyClass);
// Get the namespace of the myClass class.
Console.WriteLine("Namespace: {0}.", myType.Namespace);
Building on Joe's comment you can still use
Type myType = typeof(MyClass);
// Get the namespace of the myClass class.
var namespaceName = myType.Namespace.ToString();
with namespaceName
being a variable to access the namespace name as a string value.
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);
}
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
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;
}