Sunday, 6 March 2016

Dependency Injection in C# with Example




Dependency Injection (DI) is a design pattern that take away from the responsibility by creating a dependency class to create  loosely coupled system.Most people not clear idea about what is dependency injection (DI) and when it want to use in the code.

In this article i'm taring to describe what is dependency Injection(DI) and how we use to get loosely coupled system using simple example.Imagine you have face situation like follow


you have class Employee and it has Logger for print message.and also you have to add another Logger method for different customer,normally we can implement that as follow.

public class Employee
{
    private LoggerOne LoggerOne;
    private LoggerTwo LoggerTwo;

}

public class LoggerOne
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********",text);
    }
}

 but in this implementation Employee class tightly coupled with  LoggerOne and LoggerTwo.So this system hard to modify and reuse.

So prevent that issue we can use dependency Injection to solve this and get loosely coupled system.

  
We can use interface ILogger class for the Logger to inject the dependency to Employee class as follow

public class Employee
{
    private ReadOnly ILogger _logger;
    public Employee(ILogger Logger){
 
       _logger=Logger;
       _logger.WriteToLog("Test Logger");
    }

}

public interface ILogger
{
    void WriteToLog(string text);
}

public class LoggerOne : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}

public class LoggerTwo : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********", text);
    }
}
Now let's instantiate an Employee with two different loggers:

 Employee employee1 = new Employee(new LoggerOne());
 Employee employee2 = new Employee(new LoggerTwo());

 And the output:

 Test Logger

*******************
Test Logger
******************

Monday, 22 February 2016

LINQ Operator in C#






LINQ stands for Language Integrated Query and is Microsoft’s advanced data access technology that is used to query collections of data.


The collections can be of two types:


1.  local collections such as collections belonging to the System.Collections namespace  and the              System.Collections.Generic spaces

e.g.       List<T>,Dictionary, HashSet etc


2.  Other collections are remote collections such as an XML document or a database table

Syntax of LINQ
There are two syntaxes of LINQ. These are the following ones.

·         Lamda (Method) Syntax
Example
var longNames = Names.Where( n => n.length > 10);


·         Query (Comprehension) Syntax
Example
var longNames = from n in Names where n.length > 10;

  

Monday, 1 February 2016

How to return NULL value from generic method in C#

Following  my Example code for describe the issue,

following i have written the generic method to Search thru the list by using given search value
if value in list return the list and otherwise return NULL Value.















According to the code it seems ok.but it get following error

Cannot convert null to type parameter 'T' because it could be a value type

For avoid that issue following option

1- Method

Return default(T) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char etc

2- Method
Restrict T to be a reference type with the where T : class constraint and then return null as normal


Monday, 19 October 2015

How to Modified a Collection During in Iteration in C#

When we use Collection in our code , sometime we need to modify (delete) collection
during the Iteration. but we can't remove element directly from collection during the Iteration.
when we  do we got following Exception.

"Cannot Modify a Collection While It Is Being Iterated"


It can solve many ways in this article describe two ways to solve that  

1.Using temporary  List.
2. Can Iterate backward.

Using temporary  List

To describe this method as an example i get source Collection as customerList which the list we want to delete team during iteration. 


var tempList = customerList;      //sourceList
foreach (var item in customerList)
{
    if (item == "Bunny")       // Condition to remove Element
   {
        tempList.Remove(item);
    }
    customerList = tempList;
}



In this way, we didn't modified original collection during the iteration. for that  this method use temp collection for the modification during the iteration and finally assign  that value  to original collection.



Can Iterate backward

To describe this method as an example i get source Collection as customerList which the list we want to delete team during iteration as previous.


for (int i = customerList.Count - 1; i >= 0; i--) {
  if (customerList[i] == something) { // condition to remove element
     customerList.RemoveAt(i);
  }
}





Friday, 28 August 2015

SOLID Principal in C#


Solid principal is contains five basic principal  of OOP  and design to create good software architecture.By using these basic principal we can design, create a system that can easily maintain and extensible over time.It is part of an overall strategy of agile and adaptive programming.

SOLID is an acronym where
  • S: Single Responsibility Principle (SRP)
  • O: Open closed Principle (OSP)
  • L: Liskov substitution Principle (LSP)
  • I: Interface Segregation Principle (ISP)
  • D: Dependency Inversion Principle (DIP)





Single Responsibility Principle (SRP)