Articles → CSHARP → Tight And Loose Coupling C#

Tight And Loose Coupling C#






Tight Coupling






using System;

public class SQLDataAccess {
  public void ExecuteQuery(string query) {
    Console.WriteLine(query);
  }
}

public class ConsumerClass {
  SQLDataAccess _dal;
  public ConsumerClass(SQLDataAccess dal) {
    this._dal = dal;
  }

  public void Execute() {
    _dal.ExecuteQuery("Executing SQLDataAccess query");
  }
}

class Program {
  static void Main(string[] args) {
    ConsumerClass cc = new ConsumerClass(new SQLDataAccess());
    cc.Execute();
    Console.ReadKey();
  }
}







Loose Coupling




using System;

public interface IDatabase {
  void ExecuteQuery(string query);
}

public class SQLDataAccess: IDatabase {
  public void ExecuteQuery(string query) {
    Console.WriteLine("SQLServer query");
  }
}

public class MySQLDataAccess: IDatabase {
  public void ExecuteQuery(string query) {
    Console.WriteLine("MySQL query");
  }
}

public class ConsumerClass {
  IDatabase _dal;
  public ConsumerClass(IDatabase dal) {
    this._dal = dal;
  }

  public void Execute() {
    _dal.ExecuteQuery("Executing query");
  }
}

class Program {
  static void Main(string[] args) {
    ConsumerClass cc = new ConsumerClass(new SQLDataAccess());
    cc.Execute();

    cc = new ConsumerClass(new MySQLDataAccess());
    cc.Execute();

    Console.ReadKey();
  }
}






Picture showing the output of loose coupling in C#
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Sunday, January 8, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250