Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a type belongs to a namespace without hardcoded strings

Tags:

c#

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.

like image 960
Dante Avatar asked Jun 14 '16 12:06

Dante


2 Answers

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
like image 74
Theodoros Chatzigiannakis Avatar answered Nov 01 '22 23:11

Theodoros Chatzigiannakis


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));
like image 43
Camilo Terevinto Avatar answered Nov 01 '22 23:11

Camilo Terevinto