Tags

, ,

It is rather a translation of my previous Java post that I had posted on 26th of December.

I just translated the Java version into the C#; nothing else. For that reason, I am not going to elaborate the explanation part. If you want to know how it works, please read the previous post’s theory part.

Here I am sharing only the code that I have written in Visual Studio in Ubuntu.

First the Mobile.cs:

using System;
class Mobile {
IConnection connect;
public void getConnected(IConnection connection){
this.connect = connection; connection.setConnection(true);
if(connection.getConnection()){
Console.WriteLine("Connected through " + Cable.name);
}
}
}

The next part will show you how I need a connection Interface.

IConnection.cs

using System;
interface IConnection {
public bool getConnection();

public void setConnection(bool connection);
}

Next, I need two connectors, assuming they are Cable and WiFi which will implement that connection interface.

Cable.cs:

using System;
class Cable : IConnection {
private bool connection = false;

public static string name = "Cable";
public bool getConnection(){

return connection;

}

public void setConnection(bool connection){

this.connection = connection;

}

}

Wifi.cs:

using System;
class WiFi : IConnection {
private bool connection = false;

public static string name = "WiFi";
public bool getConnection(){

return connection;

}

public void setConnection(bool connection){

this.connection = connection;

}

}

Finally, we have the main application entry point, Program.cs:

using System;
namespace MySecondApp{

class Program {

static void Main(string[] args) {

Console.WriteLine("Hello World!");

IConnection connect = new Cable();

Mobile mob = new Mobile();

mob.getConnected(connect);

}

}

}

And if you debug this program by pressing F5, you will get this output:

Hello World!

Connected through Cable