Home
Map
using Alias ExampleUse the using alias feature, which helps resolve ambiguities in referencing type names.
C#
This page was last reviewed on Jan 16, 2024.
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.
This language feature has a limited range of use in C# programs. Typically when writing programs, using the simplest and most direct code is best.
using
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.
StringBuilder
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.
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); } }
sparky100
Complex types. More modern versions (as of 2024) of C# support aliases to many types, even generic types and tuples. Try a complex type in a using-statement and see whether it compiled.
Here We alias "Test" to the List generic class. So we can avoid specifying the type of elements elsewhere in the program.
using Test = System.Collections.Generic.List<int>; class Program { static void Main() { // Create a new List of ints. var test = new Test(); test.Add(1); test.Add(2); System.Console.WriteLine(test.Count); } }
2
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.
Directive
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.
extern alias
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 16, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.