C# Using Alias ExampleUse the using alias feature, which helps resolve ambiguities in referencing type names.
Using alias. A using alias directive introduces new type names. These point to an existing type or namespace. This provides more flexibility should the implementation need to change.
A language feature. This feature has a limited range of use in the C# programs. Typically when writing programs, using the simplest and most direct code is best.
Syntax chart. Consider we want to use the name "Cat" to refer to a StringBuilder. This could be the .NET StringBuilder, or a different one we implement elsewhere.
Syntax notes:
USING ALIAS: using Cat = System.Text.StringBuilder;
Example. The using alias directive syntax requires the "using" keyword and then the equals sign. Then an existing type name or namespace is required.
Here We map the type "Cat" to the type "System.Text.StringBuilder". In the program, the type Cat can be used as a StringBuilder.
C# program that shows using alias directive
using System; using Cat = System.Text.StringBuilder; class Program { static void Main() { Cat cat = new Cat(); cat.Append("sparky"); cat.Append(100); Console.WriteLine(cat); } }
Discussion, debug. Sometimes, an entire program would want to use one type implementation for DEBUG mode, and a different implementation for RELEASE mode.
And You could use an alias instead of the actual type names. Then you could use #ifdef and #else to wrap the using alias directive.
If, Elif, Endif
Resolve ambiguities. Say you have a custom StringBuilder type in the namespace Perls.Animals.StringBuilder. And you include System.Text and this other namespace.
Then The using alias directive can specify what "StringBuilder" actually points to.
A summary. Like "extern," using alias helps resolve ambiguities in programs. It can also enable you to swap implementations for a type based on compile-time flags.
A final note. The major drawback is that this syntax can result in programs that are confusing. Confusing programs should be avoided.
© 2007-2021 sam allen. see site info on the changelog