C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Using Static Directive (Static Import)C# using static directive helps us to access static members (methods and fields) of the class without using the class name. If we don?t use static directive, we need to use class name to call static members each time. It allows us to import static members of a class into the source file. It follows a syntax that is given below. C# using static directive syntaxusing static <fully-qualified-type-name> In the following example, we are not using static directive. We can see that, to access static method of Math class, class name is used. C# Example without using static directiveusing System; namespace CSharpFeatures { class StaticImport { public static void Main(string[] args) { double sqrt = Math.Sqrt(144); // Math class is used to access Sqrt() method string newStr = String.Concat("TheDeveloperBlog",".com"); Console.WriteLine(sqrt); Console.WriteLine(newStr); } } } Output 12 TheDeveloperBlog.com In the following example, we are using static directive in the source file. So, it does not require class name before calling the method. C# Example with using static directiveusing System; using static System.Math; // static directive using static System.String; namespace CSharpFeatures { class StaticImport { public static void Main(string[] args) { double sqrt = Sqrt(144); // Calling without class name string newStr = Concat("TheDeveloperBlog",".com"); Console.WriteLine(sqrt); Console.WriteLine(newStr); } } } We can see, it produces the same result even after removing the type from the function call. Output 12 TheDeveloperBlog.com
Next TopicC# Exception Filters
|