RcBuilder@walla.com
call centre: 054-5614020

implicit cast to return a single instance object

29
May
2014
Posted by: RcBuilder  /   Category: Converters / Extensions / implicit / Reference Types / SOURCE CODE   /   No Comments

using implicit cast to return a single instance object

/*
the abillity to return a single instance for multiple objects using implicit cast
we defined 2 classes (class1 and class2) and we define 2 services (service1 and service2)
each service DoWork method should return a different object type (service1 return class1 and service2 return class2)

demand:
we want to share it to return a single instance with the ability to contains class1 or class2 in order to prevent unnecessary conditions in our code

solution:
we created a new class (class3) and defined 2 implicit converts (for both class1 and class2)
and set our services to return our new class3
that way we cound return a single instance for both services

example:
var service1 = new Service1();
var service2 = new Service2();

for (int i = 0; i < 10; i++)
{
var response = DateTime.Now.Ticks % 2 == 0 ? service1.DoWork() : service2.DoWork();
Console.WriteLine(response);
Thread.Sleep(100);
}
*/

public class Class1
{
public string p1 { private set; get; }
public string p2 { private set; get; }

public Class1(string p1, string p2) {
this.p1 = p1;
this.p2 = p2;
}
}

public class Class2
{
public string p1 { private set; get; }
public string p2 { private set; get; }

public Class2(string p1, string p2) {
this.p1 = p1;
this.p2 = p2;
}
}

public class Class3 {
public string p1 { private set; get; }
public string p2 { private set; get; }

public static implicit operator Class3(Class1 c) // implicit Convert Class1 to Class3
{
return new Class3() { p1 = c.p1, p2 = c.p2 };
}

public static implicit operator Class3(Class2 c) // implicit Convert Class2 to Class3
{
return new Class3() { p1 = c.p1, p2 = c.p2 };
}

public override string ToString()
{
return string.Concat(“HELLO FROM “, this.p1, ” “,this.p2);
}
}

interface iService {
Class3 DoWork();
}

public class Service1 : iService {
public Class3 DoWork(){
return new Class1(“CLASS”, “1″);
}
}

public class Service2 : iService {
public Class3 DoWork() {
return new Class2(“CLASS”, “2″);
}
}

Author Avatar

About the Author

בניית אתרים ופתרונות טכנולוגים | RcBuilder

No Comments


  • פיתוח מערכות
  • פתרונות טכנולוגים
  • קידום אתרים
  • בניית אתרים