Can I create an alias in C # or VB.NET in the method scope?

Is there any equivalent to an aliasing instruction like:

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

      

or

' VB.NET '
Imports C = System.Console

      

... but within scope - instead of applying to the entire file?

+2


a source to share


3 answers


While this might be overkill, you can create a partial class and only place the functions you want the alias to apply in its own aliased file.

In the main class file:

/*Existing using statements*/   

namespace YourNamespace
{
    partial class Foo
    {

    }
}

      



In another file:

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

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

      

+3


a source


Using an object reference would be logical. You put an obstacle using a static class. It worked 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

      

+2


a source


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

      

0


a source







All Articles