Search code examples
c#.netnamespaces.net-assembly

Reference a public static class in the global namespace in another assembly


In C#, is there a way to access a public static class in the global namespace in assembly A from assembly B (assuming assembly B references assembly A), when assembly B has public static class in the global namespace that has the same name? For example in Bar.cs in assembly A:

using System.Diagnostics;
// NOTE: No namespace declared here - this is in the global:: ns
public static class Bar
{
    public static void DoSomethingSilly()
    {
        Debug.WriteLine("I'm silly!");
    }
}

How could I use this in Bar.cs in assembly B?

public static class Bar
{
    public static void DoSomethingSilly()
    {
        // call Bar.DoSomethingSilly() from assembly A here
    }
}

I tried things like global::Bar.DoSomethingSilly(), which doesn't work in assembly B (it just gets me the reference back to assembly B).

I also know I could use reflection to get at it (something like Assembly.GetType()), but I'm more wondering if there's some native C# syntax for it. In the end I added a namespace around the code in assembly A, which I own and which was only in the global namespace because it was generated by another tool - adding the namespace didn't cause any problems, but I'm curious if there's syntax to allow this kind of referencing.


Solution

  • Thanks to @Jon Skeet for this direction - extern alias is what can make this work. On the properties for the reference to the assembly, add an alias (for example assemblyA, or in the screen shot taken from here FooVersion1):

    property window example

    , and at the top of the .cs file add:

    extern alias assemblyA;
    

    which will then allow either:

    assemblyA::Foo.DoSomethingSilly();
    assemblyA.Foo.DoSomethingSilly();
    

    I still went for adding a namespace to the generated code - it's more straightforward and avoids polluting the global namespace.