DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Using Struct as Directive in C# 6 & C# 7

AS we know that before C# 6 we use to include only namespaces as “using directive” But in C# 6 & C# 7 we can include static classes, enum, non-static classes & structs too as “using directive”.

In this code snippet I am going to show you a sample code for “using Struct as directive” so that you can aware about its syntax and usage. You may be interested in code snippet of,

1.   1. Using Static Classes as directive

2.   2. Using non-Static classes as directive

3.   3. Using Enum as directive

Below is the code snippet of “Using Struct as directive”,

  1. using static System.Drawing.Color; //struct  
  2. using static System.DateTime; //struct  
  3. using static System.Console;  
  4.   
  5. namespace UsingStructAsDirectiveinCSharp6n7  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             //you may need to add System.Drawing assembly reference   
  12.             //for "using static System.Drawing.Color"  
  13.             var color =Red; //System.Drawing.Color              
  14.   
  15.             var isLeapyear = IsLeapYear(2016); //System.DateTime  
  16.   
  17.             WriteLine($"Today is: " + Now.DayOfWeek); //System.DateTime            
  18.   
  19.         }  
  20.     }  
  21. }  

Learn C# 6

Learn C# 6 new features by the dozen of articles written by Banketeshvar Narayan.



Using Static Classes as Directive in C# 6

As we know that in C# 6 we can use static classes in using directive. To use static classes in using directive we use the following syntax:

Using static <StaticClassNameWithCompleteNameSpace>;

  1. using System;  
  2. using static System.Console;  
  3. using static System.Convert;  
  4.   
  5. namespace UsingStaticToPrintDay  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             try  
  12.             {  
  13.                 WriteLine("Enter you choice from 1-7 and it will print corresponding day of a week");  
  14.                 int choiceofday  = ToInt32(ReadLine());    
  15.                 //Cast int to Enum                
  16.                 string dayOfweek = Enum.GetName(typeof(DayOfWeek), choiceofday);  
  17.                 WriteLine(dayOfweek);                
  18.             }  
  19.             catch (Exception ex)  
  20.             {  
  21.                 WriteLine(ex.Message);  
  22.             }  
  23.              
  24.               
  25.         }  
  26.     }  
  27. }