Mastering C# Using Statements: Imports, Aliases, and Static Directives
C# Using Statements
This tutorial explores how to leverage the C# using keyword for importing namespaces, creating aliases, and accessing static members. Practical examples illustrate each technique.
In C#, the using directive brings external resources—such as namespaces and classes—into scope. This eliminates the need to write fully qualified names throughout your code.
// Import the System namespace
using System;
namespace Program {
class Program1 {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
}
}
Output
Hello World!
Notice the line using System;; it allows direct use of classes like Console without the System. prefix.
// Fully qualified
System.Console.WriteLine("Hello World!");
// With using System
Console.WriteLine("Hello World!");
For more on namespaces, see C# namespaces.
Creating Aliases with using
You can assign a shorthand name to a type, simplifying repetitive references.
// Alias System.Console as Programiz
using Programiz = System.Console;
namespace HelloWorld {
class Program {
static void Main(string[] args) {
// Use the alias instead of the full type
Programiz.WriteLine("Hello World!");
}
}
}
Output
Hello World!
The alias Programiz behaves identically to System.Console, but reduces verbosity.
Using using static for Static Members
Static members of a class—fields, properties, and methods—can be accessed directly when the class is imported with using static.
Example: Importing System.Math
using System;
// Import static members of Math
using static System.Math;
namespace Program {
class Program1 {
public static void Main(string[] args) {
double n = Sqrt(9);
Console.WriteLine("Square root of 9 is " + n);
}
}
}
Output
Square root of 9 is 3
Because of using static System.Math;, Sqrt is invoked without the Math. qualifier.
Without the static import:
using System;
namespace Program {
class Program1 {
public static void Main(string[] args) {
double n = Math.Sqrt(9);
Console.WriteLine("Square root of 9 is " + n);
}
}
}
Output
Square root of 9 is 3
Here, the full class name is required because the static directive is omitted.
C Language
- LM35‑Based Temperature Control System Using AT89S52 Microcontroller
- Mastering IPython: Boost Your Python Productivity
- Java 9 Module System: Enhancements, Link‑Time, and Custom Runtime Images
- Mastering C# Exception Handling: Strategies & Best Practices
- Smart Plant Monitoring System Powered by AWS IoT
- Advanced Smart Waste Monitoring with Arduino 101: BLE & WiFi Integration
- Mastering DSP Handle Usage: Key Guidelines for Optimal Performance
- Students Build Advanced B&R-Powered Robotic Garbage‑Sorting System
- PLC vs DCS: Choosing the Right Automation System
- 5 Key Advantages of a Warehouse Execution System for Modern Supply Chains