Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string is a namespace

I have a string and I want to check if it represents a proper namespace, eg. System.IO is ok, but System.Lol is not.

I guess some reflection should be used, but I can't figure this out.

Any thoughts?

like image 964
Darmak Avatar asked Apr 09 '10 09:04

Darmak


2 Answers

Try this approach:

using System.CodeDom.Compiler;
using System.Linq;

class NamespaceTester : IDisposable
{
    private CodeDomProvider provider = CodeDomProvider.CreateProvider("c#");
    private CompilerParameters settings = new CompilerParameters();
    private CompilerResults results;

    public bool Test(string[] namespaces)
    {
        results = provider.CompileAssemblyFromSource(
            settings,
            namespaces.Select(n => String.Format("using {0};", n)).ToArray());
        return results.Errors
            .OfType<CompilerError>()
            .Any(e => String.Equals(
                e.ErrorText,
                "CS0234",
                StringComparison.Ordinal));
    }

    public void Dispose()
    {
        if (results != null)
        {
            System.IO.File.Delete(results.CompiledAssembly.Location);
        }
    }
}

where CS0234 is:

The type or namespace name 'name' does not exist in the class or namespace 'scope' (are you missing an assembly reference?)

Custom references adding:

settings.ReferencedAssemblies.Add("Foobar.dll")

Usage:

public static void Main(string[] args)
{
    using (var tester = new NamespaceTester())
    {
        var success = tester.Test(new[] {
            "System.IO",
            "System.LOL"
        });
    }
}
like image 98
abatishchev Avatar answered Nov 12 '22 17:11

abatishchev


Your question "How to check if string is a namespace" is only valid when you consider where you are checking for namespaces.

Namespaces are prefixes to class names, and classes are scoped to an assembly. To check whether a namespace exists, you need to decide which assemblies you are prepared to look through to find the existence of the namespace.

Once you have decided which assemblies you are prepared to look through, you can iterate through them for the existence of a particular namespace like so:

public bool NamespaceExists(IEnumerable<Assembly> assemblies, string ns)
{
    foreach(Assembly assembly in assemblies)
    {
        if(assembly.GetTypes().Any(type => type.Namespace == ns))
            return true;
    }

    return false;
}
like image 4
Paul Turner Avatar answered Nov 12 '22 19:11

Paul Turner