2

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?

2
  • 1
    What would be a use case for such an alias? I can't think of any situation where this might be helpful. Commented May 11, 2010 at 14:35
  • 0xA3: I would imagine that he might wish to dynamically redirect a particular method to use a different class by the same name without changing any code. Not that I'm necessarily endorsing such a use, but it would/could make such a task easier, if not altogether intuitive. Commented May 11, 2010 at 14:39

3 Answers 3

3

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");
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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{}
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.