Is it possible to check if a type is part of a namespace without using harcoded strings?
I'm trying to do something like:
Type type = typeof(System.Data.Constraint);
if(type.Namespace == System.Data.ToString())
{...}
or
Type type = typeof(System.Data.Constraint);
if(type.Namespace == System.Data)
{...}
to avoid
Type type = typeof(System.Data.Constraint);
if(type.Namespace == "System.Data")
{...}
These examples don't compile but should give an idea of what I'm trying to achieve.
I can't use nameof(System.Data) because it only returns "Data".
I would like to find a way to check if a class if part of a namespace without the need to have that namespace in a string.
You can define this in the namespace where you want to perform the check:
static class Namespace
{
    public static bool Contains<T>() 
        => typeof (T).Namespace == typeof (Namespace).Namespace;
}    
For example:
namespace My.Inner
{
    static class Namespace
    {
        public static bool Contains<T>()
            => typeof (T).Namespace == typeof (Namespace).Namespace;
    }    
}
Two types as test cases:
namespace My
{
    class SomeTypeA { }
}
namespace My.Inner
{
    class SomeTypeB { }
}
Here is the usage:
Console.WriteLine(My.Inner.Namespace.Contains<SomeTypeA>()); // False
Console.WriteLine(My.Inner.Namespace.Contains<SomeTypeB>()); // True
                        You should be able to do something like this:
static class Namespaces
{
    //You would then need to add a prop for each namespace you want
    static string Data = typeof(System.Data.Constrains).Namespace;
}
var namespaceA = typeof(System.Data.DataTable).Namespace
if (namespaceA == Namespaces.Data) //true
{ 
    //do something
}
Also, using the idea from @Theodoros Chatzigiannakis, you could further generalize this:
static class Namespace
{
    //generic
    static bool Contains<T1, T2>()
    {
        return typeof(T1).Namespace == typeof(T2).Namespace;
    }
    //Non-generic
    static bool Contains(Type type1, Type type2)
    {
        return type1.Namespace == type2.Namespace;
    }
}
And then use it like:
bool generic = Namespace.Contains<System.Data.CLASS1, System.Data.CLASS2>();
bool nonGeneric = Namespace.Contains(typeof(System.Data.CLASS1), typeof(System.Data.CLASS2));
                        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