views:

152

answers:

3

Is there any equivalent to an aliasing statement such as:

// C#:
using C = System.Console;

or:

' VB.NET '
Imports C = System.Console

...but within method scope -- rather than applying to an entire file?

+3  A: 

While this might be overkill, you could create a partial class and place only the functions you'd like the alias to apply to in their own file with the alias.

In the main class file:

/*Existing using statements*/   

namespace YourNamespace
{
    partial class Foo
    {

    }
}

In the other file:

/*Existing using statements*/   
using C = System.Console;

namespace YourNamespace
{
    partial class Foo
    {
        void Bar()
        {
            C.WriteLine("baz");
        }
    }
}
Adam Robinson
A: 

See here and here for more details.

Example:

namespace PC
{
    // Define an alias for the nested namespace.
    using Project = PC.MyCompany.Project;
    class A 
    {
        void M()
        {
            // Use the alias
            Project.MyClass mc = new Project.MyClass();
        }
    }
    namespace MyCompany
    {
        namespace Project
        {
            public class MyClass{}
        }
    }
}
sashaeve
+1  A: 

Using an object reference would be the logical way. You are putting up a bit of an obstacle by using a static class. Worked around like this:

   var c = Console.Out;
   c.WriteLine("hello");
   c.WriteLine("world");

Or the VB.NET With statement:

    With Console.Out
        .WriteLine("hello")
        .WriteLine("world")
    End With
Hans Passant