DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

C# 8.0 - Experimenting With Non-Nullable Reference Type Using Visual Studio 2017

Nullable Reference Type is one of the most popular upcoming features of C# which may be released with C# 8.0. However, since C# 8.0 has not been released yet and the development is going on, so till the final release, its behavior may be a little bit different than the current behavior explained in this article.

Many discussions are going on in developer’s communities about C# 8.0 Nullable reference type, and most of us are referring it to a breaking change. However, in my opinion, it is a significant change but not a breaking change. Read More >>

Break Vs Continue in C#

Break and continue is a very basic concept of any programming language and I think it is supported by almost all popular languages e.g. C++, C#, Java, JavaScript, etc. I know that most of us know about it very well but for fresher guys its little bit confusing. So, I am explaining here so that even fresher can understand and use it easily.

Break (breaks the loop/switch)

Break statement is used to terminate the current loop iteration or terminate the switch statement in which it appears  Read More >>

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. }  

Variable.ToString() vs. Convert.ToString(variable)

variable.ToString() and Convert.ToString(variable) both are used for converting data into string. But the main difference is that Convert.ToString() handles null, while ToString() doesn't handle null value.

Apart from that both works almost same. Let’s take an example to explain it:
  1. double amount = 10000.0;  
  2. Console.WriteLine(amount.ToString());  
  3. Console.WriteLine(Convert.ToString(amount));   
In this case both method will convert “amount” to string and will return the same value but in case of null value variable.ToString() method will throw exception.

Now take another example:

  1. object myObject = null;  
  2. string myString;  
  3.   
  4. //myString = myObject.ToString();  
  5. // System.NullReferenceException : { "Object reference not set to an instance of an object."}  
  6.   
  7. myString = Convert.ToString(myObject);  
  8. //return empty string

Getting More than 2 Values for an Enum Item

As we know that we can get Enum and it value from an Enum type e.g. I want to create an enum for sorting of article like below:

  1. enum ArticleSortingOptions  
  2. {  
  3.    MostPopularArticle =1,  
  4.    LatestArticles =2,  
  5.    FeaturedArtilces =3,  
  6.    MostLikedArtilces =4,  
  7.    MostCommentedArtilces=5  
  8. }  

And accessing it like

  1. WriteLine(MostPopularArticle.ToString());  
  2. WriteLine((int)MostPopularArticle);  

Output

MostPopularArticle

1

you may be thinking that I am aceesing enum item without enum name. Yes, it is possible in C# 6 & C# 7 that we can acess enum items without enum name for that we have to write enum name in using statement i.e.

  1. using static MultiValuedEnum.ArticleSortingOptions;  

You will never prefer to display the value like “MostPopularArticle” but to be displayed like “Most Popular Article”. As we know that enum will not allow you to write an item with spaces. So we will require 3 types of values

1. Integer value of enum item.

2.   2. Name of enum Item (string Value of enum).

3.   3. Description of Enum (or some other value as per requirement).

We can achieve this by writing and extension method for enum.

  1. public static class ExtendEnum  
  2. {  
  3.    public static string DisplayString<T>(this T enumVal)  
  4.    {  
  5.       FieldInfo fi = enumVal.GetType().GetField(enumVal.ToString());  
  6.       var attrs = fi?.GetCustomAttributes(typeof(DescriptionAttribute), true);  
  7.       if (attrs != null && attrs.Length > 0)  
  8.       {  
  9.          return ((DescriptionAttribute)attrs[0]).Description;  
  10.       }  
  11.       return "No Description found";  
  12.    }  
  13. }  

And access like:

  1. WriteLine(MostPopularArticle.ToString());  
  2. WriteLine((int)MostPopularArticle);  
  3. WriteLine(MostPopularArticle.DisplayString());  

Complete Code:

  1. using System.ComponentModel;  
  2. using System.Reflection;  
  3. using static MultiValuedEnum.ArticleSortingOptions;  
  4. using static System.Console;  
  5.   
  6. namespace MultiValuedEnum  
  7. {  
  8.     enum ArticleSortingOptions  
  9.     {  
  10.         [Description("Most Popular Article")]  
  11.         MostPopularArticle = 1,          
  12.         LatestArticles = 2,  
  13.         FeaturedArtilces = 3,  
  14.         MostLikedArtilces = 4,  
  15.         MostCommentedArtilces = 5  
  16.     }  
  17.     class Program  
  18.     {  
  19.         static void Main(string[] args)  
  20.         {  
  21.             WriteLine(MostPopularArticle.ToString());  
  22.             WriteLine((int)MostPopularArticle);  
  23.             WriteLine(MostPopularArticle.DisplayString());  
  24.         }  
  25.     }  
  26.   
  27.     public static class ExtendEnum  
  28.     {  
  29.         public static string DisplayString<T>(this T enumVal)  
  30.         {  
  31.             FieldInfo fi = enumVal.GetType().GetField(enumVal.ToString());  
  32.             var attrs = fi?.GetCustomAttributes(typeof(DescriptionAttribute), true);  
  33.             if (attrs != null && attrs.Length > 0)  
  34.             {  
  35.                 return ((DescriptionAttribute)attrs[0]).Description;  
  36.             }  
  37.             return "No Description found";  
  38.         }  
  39.     }  
  40. }  

Output

MostPopularArticle

1

Most Popular Article

Converting Enum to Different Format

  1.  //way 1              
  2.  Enum MyNewEnum = (MyColors)Enum.Parse(typeof(MyColors), "RED");         
  3.   
  4.  //Way 2   
  5.  Enum MyNewEnum2 = (MyColors)Enum.Parse(typeof(MyColors), "1");  
  6.   
  7.  //Way 3  
  8.  Enum MyNewEnum3 = (MyColors)1;  
  9.   
  10.  //Way 4  
  11.  Enum MyNewEnum4 = (MyColors)Enum.ToObject(typeof(MyColors), 1);  
  12.   
  13.  //Way 5  
  14.  Enum MyNewEnum5 = (MyColors)3;  
  15.   
  16.  //Way 6  
  17.  string myEnumString  = ((MyColors)1).ToString("F");  
  18.  string myEnumString2 = ((MyColors)1).ToString("F");  
  19.   
  20.  string myEnumString3 = MyColors.BLUE.ToString("d");  
  21.  string myEnumString4 = MyColors.BLUE.ToString("D");  
  22.                                  
  23.  string myEnumString5 = MyColors.BLUE.ToString("g");  
  24.  string myEnumString6 = MyColors.BLUE.ToString("G");  
  25.                                  
  26.  string myEnumString7 = MyColors.BLUE.ToString("x");  
  27.  string myEnumString8 = MyColors.BLUE.ToString("X");  
  28.   
  29.  //Way 7  
  30.  string[] colorrList  = Enum.GetNames(typeof(MyColors));  
  31.  string myEnumString9 = Enum.GetName(typeof(MyColors), 5);  
  32.   
  33.  //way 8  
  34. string myFormatEnumString1 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "d");  
  35. string myFormatEnumString2 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "D");  
  36. string myFormatEnumString3 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "f");  
  37. string myFormatEnumString4 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "F");  
  38. string myFormatEnumString5 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "g");  
  39. string myFormatEnumString6 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "G");  
  40. string myFormatEnumString7 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "x");  
  41. string myFormatEnumString8 = Enum.Format(typeof(MyColors), MyColors.ORANGE, "X");  

Learn C # 7.x (articles on C# 7.0, C# 7.1 & 7.2 new features)

  



Learn C# 7.0, C# 7.1 & C# 7.2 new features by the collection of articles written by Banketeshvar Narayan


Learn C# 6

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



Using Non-Static classes in using block as directive in C# 6

It is a misconception that “using static” keyword is used to including only static classes as a directive in C# 6. But I have checked it in Visual Studio 2015 and it can also include Non-static classes.

E.g.

Class1.cs
  1. namespace UsingStatic1  
  2. {  
  3.     public class Class1  
  4.     {  
  5.         public static int Add(int x, int y)  
  6.         {  
  7.             return x + y;  
  8.         }  
  9.     }  
  10. }  

Program.cs
  
  1. using static UsingStatic1.Class1;  
  2. namespace UsingStatic  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int i = Add(20, 30);  
  9.         }  
  10.     }  
  11. }  
  UsingStatic1.Class1  is a non-static class and value of i will be 20+30=50;

Read Write and Update XML using LINQ Queries

I am going to take a Simple XML data and will show how to read write and Update it using LINQ.

Sample XML File:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LumiaMobiles>  
  3.   <LumiaMobile>  
  4.     <ModelId>lumia550</ModelId>  
  5.     <Height>136.1 mm</Height>  
  6.     <Width>67.8 mm</Width>  
  7.     <Thickness>9.9 mm</Thickness>  
  8.     <Weight>141.9 g</Weight>  
  9.   </LumiaMobile>  
  10.   <LumiaMobile>  
  11.     <ModelId>lumia950</ModelId>  
  12.     <Height>145 mm</Height>  
  13.     <Width>73.2 mm</Width>  
  14.     <Thickness>8.2 mm</Thickness>  
  15.     <Weight>150 g</Weight>  
  16.   </LumiaMobile>  
  17. </LumiaMobiles>  

Corresponding class for XML Data:

  1. public class LumiaMobile  
  2. {  
  3.    public string ModelId { getset; }  
  4.    public string Height { getset; }  
  5.    public string Width { getset; }  
  6.    public string Thickness { getset; }  
  7.    public string Weight { getset; }  
  8. }  

Code to Write XML File 

  1. private void WriteLumiaMobilesDetails(List<LumiaMobile> lstLumiaMobiles)  
  2. {  
  3.     using (XmlWriter writer = XmlWriter.Create("LumiaMobiles2.xml"))  
  4.     {  
  5.         writer.WriteStartDocument();  
  6.         writer.WriteStartElement("LumiaMobiles");  
  7.         foreach (var mobile in lstLumiaMobiles)  
  8.         {  
  9.             writer.WriteStartElement("LumiaMobile");  
  10.             writer.WriteElementString("ModelId", mobile.ModelId);  
  11.             writer.WriteElementString("Height", mobile.Height);  
  12.             writer.WriteElementString("Width", mobile.Width);  
  13.             writer.WriteElementString("Thickness", mobile.Thickness);  
  14.             writer.WriteElementString("Weight", mobile.Weight);  
  15.             writer.WriteEndElement();  
  16.         }  
  17.   
  18.         writer.WriteEndElement();  
  19.         writer.WriteEndDocument();  
  20.     }  
  21. }  

Calling Write XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.     Program p = new Program();              
  4.     List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  5.     lstLumiaMobiles.Add(new LumiaMobile  
  6.     {  
  7.         ModelId = "lumia550",  
  8.         Height = "136.1 mm",  
  9.         Width = "67.8 mm",  
  10.         Thickness = "9.9 mm",  
  11.         Weight = "141.9 g"  
  12.     });  
  13.   
  14.     lstLumiaMobiles.Add(new LumiaMobile  
  15.     {  
  16.         ModelId = "lumia950",  
  17.         Height = "145 mm",  
  18.         Width = "73.2 mm",  
  19.         Thickness = "8.2 mm",  
  20.         Weight = "150 g"  
  21.     });  
  22.     p.WriteLumiaMobilesDetails(lstLumiaMobiles);              
  23. }  

Code to Read XML Data:

  1. public List<LumiaMobile> ReadLumiaMobilesDetails()  
  2. {  
  3.     List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  4.     try  
  5.     {  
  6.         using (XmlReader xr = XmlReader.Create(@"LumiaMobiles.xml"))  
  7.         {  
  8.             XDocument xdoc = XDocument.Load(xr);  
  9.             var LumiaMobiles = xdoc.Descendants("LumiaMobiles").Descendants("LumiaMobile");  
  10.             foreach (var mobile in LumiaMobiles)  
  11.             {  
  12.                 lstLumiaMobiles.Add(new LumiaMobile  
  13.                 {  
  14.                     ModelId = Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value),  
  15.                     Height = Convert.ToString(mobile.Descendants("Height").FirstOrDefault().Value),  
  16.                     Width = Convert.ToString(mobile.Descendants("Width").FirstOrDefault().Value),  
  17.                     Thickness = Convert.ToString(mobile.Descendants("Thickness").FirstOrDefault().Value),  
  18.                     Weight = Convert.ToString(mobile.Descendants("Weight").FirstOrDefault().Value)  
  19.                 });  
  20.             }  
  21.         }  
  22.     }  
  23.     catch (Exception)  
  24.     {  
  25.   
  26.     }  
  27.     return lstLumiaMobiles;  
  28. }  

Calling Read XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.    Program p = new Program();  
  4.    p.ReadLumiaMobilesDetails();   
  5. }  

Code to Update XML Data:

  1. private void UpdateXmlElementforMobile(string ModelId, string element, string elementValue)  
  2. {  
  3.   
  4.     XDocument xdoc = XDocument.Load("LumiaMobiles.xml");  
  5.     var LumiaMobiles = xdoc.Descendants("LumiaMobile");  
  6.     foreach (var mobile in LumiaMobiles)  
  7.     {  
  8.         if (mobile.Descendants("ModelId").Any())  
  9.         {  
  10.             if (Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value) == ModelId)  
  11.             {  
  12.                 mobile.Descendants(element).FirstOrDefault().Value = elementValue;  
  13.                 xdoc.Save("LumiaMobiles.xml");  
  14.             }  
  15.         }  
  16.     }  
  17. }  

Calling Update XML Data Method: 

  1. static void Main(string[] args)  
  2. {  
  3.    Program p = new Program();  
  4.    p.UpdateXmlElementforMobile("lumia950""Height""145.0 mm");  
  5. }  

Complete Code is:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Xml;  
  5. using System.Xml.Linq;  
  6.   
  7. namespace XMLtoLINQ  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             Program p = new Program();  
  14.             p.ReadLumiaMobilesDetails();  
  15.             List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  16.             lstLumiaMobiles.Add(new LumiaMobile  
  17.             {  
  18.                 ModelId = "lumia550",  
  19.                 Height = "136.1 mm",  
  20.                 Width = "67.8 mm",  
  21.                 Thickness = "9.9 mm",  
  22.                 Weight = "141.9 g"  
  23.             });  
  24.   
  25.             lstLumiaMobiles.Add(new LumiaMobile  
  26.             {  
  27.                 ModelId = "lumia950",  
  28.                 Height = "145 mm",  
  29.                 Width = "73.2 mm",  
  30.                 Thickness = "8.2 mm",  
  31.                 Weight = "150 g"  
  32.             });  
  33.   
  34.             p.WriteLumiaMobilesDetails(lstLumiaMobiles);  
  35.   
  36.             p.UpdateXmlElementforMobile("lumia950""Height""145.0 mm");  
  37.         }  
  38.   
  39.         private void UpdateXmlElementforMobile(string ModelId, string element, string elementValue)  
  40.         {  
  41.   
  42.             XDocument xdoc = XDocument.Load("LumiaMobiles.xml");  
  43.             var LumiaMobiles = xdoc.Descendants("LumiaMobile");  
  44.             foreach (var mobile in LumiaMobiles)  
  45.             {  
  46.                 if (mobile.Descendants("ModelId").Any())  
  47.                 {  
  48.                     if (Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value) == ModelId)  
  49.                     {  
  50.                         mobile.Descendants(element).FirstOrDefault().Value = elementValue;  
  51.                         xdoc.Save("LumiaMobiles.xml");  
  52.                     }  
  53.                 }  
  54.             }  
  55.         }  
  56.   
  57.         private void WriteLumiaMobilesDetails(List<LumiaMobile> lstLumiaMobiles)  
  58.         {  
  59.             using (XmlWriter writer = XmlWriter.Create("LumiaMobiles2.xml"))  
  60.             {  
  61.                 writer.WriteStartDocument();  
  62.                 writer.WriteStartElement("LumiaMobiles");  
  63.                 foreach (var mobile in lstLumiaMobiles)  
  64.                 {  
  65.                     writer.WriteStartElement("LumiaMobile");  
  66.                     writer.WriteElementString("ModelId", mobile.ModelId);  
  67.                     writer.WriteElementString("Height", mobile.Height);  
  68.                     writer.WriteElementString("Width", mobile.Width);  
  69.                     writer.WriteElementString("Thickness", mobile.Thickness);  
  70.                     writer.WriteElementString("Weight", mobile.Weight);  
  71.                     writer.WriteEndElement();  
  72.                 }  
  73.   
  74.                 writer.WriteEndElement();  
  75.                 writer.WriteEndDocument();  
  76.             }  
  77.         }  
  78.   
  79.         public List<LumiaMobile> ReadLumiaMobilesDetails()  
  80.         {  
  81.             List<LumiaMobile> lstLumiaMobiles = new List<LumiaMobile>();  
  82.             try  
  83.             {  
  84.                 using (XmlReader xr = XmlReader.Create(@"LumiaMobiles.xml"))  
  85.                 {  
  86.                     XDocument xdoc = XDocument.Load(xr);  
  87.                     var LumiaMobiles = xdoc.Descendants("LumiaMobiles").Descendants("LumiaMobile");  
  88.                     foreach (var mobile in LumiaMobiles)  
  89.                     {  
  90.                         lstLumiaMobiles.Add(new LumiaMobile  
  91.                         {  
  92.                             ModelId = Convert.ToString(mobile.Descendants("ModelId").FirstOrDefault().Value),  
  93.                             Height = Convert.ToString(mobile.Descendants("Height").FirstOrDefault().Value),  
  94.                             Width = Convert.ToString(mobile.Descendants("Width").FirstOrDefault().Value),  
  95.                             Thickness = Convert.ToString(mobile.Descendants("Thickness").FirstOrDefault().Value),  
  96.                             Weight = Convert.ToString(mobile.Descendants("Weight").FirstOrDefault().Value)  
  97.                         });  
  98.                     }  
  99.                 }  
  100.             }  
  101.             catch (Exception)  
  102.             {  
  103.   
  104.             }  
  105.             return lstLumiaMobiles;  
  106.         }  
  107.     }  
  108.   
  109.     public class LumiaMobile  
  110.     {  
  111.         public string ModelId { getset; }  
  112.         public string Height { getset; }  
  113.         public string Width { getset; }  
  114.         public string Thickness { getset; }  
  115.         public string Weight { getset; }  
  116.     }  
  117. }