Social Icons

Pages

Monday, January 14, 2019

Write Cleaner Code C#


Some of the C# features that will help you write cleaner code

1. Initialize Constructor

Common way
  class BLWriteCleanerCode
    {
        public DateTime CreatedDate { get;   }
        public List<Employee> Employees { get; }

        public  BLWriteCleanerCode()
        {
            CreatedDate = DateTime.Now;
            Employees = new List<Employee>();
        }
    }

With C# 6, you can initialize the property directly
    class BLWriteCleanerCode
    {
        public DateTime CreatedDate { get; } = DateTime.Now;
        public List<Employee> Employees { get; } = new List<Employee>();

    }

2. Create Dictionary
Common way
var employees = new Dictionary<intstring>
            {
                 { 1, "John" },
                 { 2, "Mathy" }
            };

New way
      var employees = new Dictionary<intstring>
            {
                [1] = "John",
                [2] = "Mathy"
            };

3. Using String

Common way
        var emploueeData = String.Format("{0} ({1})", emp.EmployeeID, emp.EmployeeName);

New way
var emploueeData = $"{emp.EmployeeID}{emp.EmployeeName}";

4. Using Null-conditional Operator

Common way
        Employee emp;
        List<Employee> empCollection = new List<Employee>();
        if (empCollection != null)
            emp = empCollection[0];

New way
           emp = empCollection?[0];

Common way
        if (empCollection[0] != null)
           {
               if (empCollection[0].Address != null)
               {
                    address = empCollection[0].Address[0].Address1;
               }
           }
New way

address = empCollection[0]? .Address[0]?.Address1??"" ;