RcBuilder@walla.com
call centre: 054-5614020

implicit C#

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

implicit C#

structure:

public static implicit operator Class3(Class1 c); // implicit Convert Class1 to Class3
public static implicit operator Class3(string s); // implicit Convert string to Class3
public static implicit operator string(Class3 c); // implicit class3 to string

example:

public class ClassA
{
public string FName { private set; get; }
public string LName { private set; get; }
public byte Age { private set; get; }

public ClassA(string FName, string LName, byte Age)
{
this.FName = FName;
this.LName = LName;
this.Age = Age;
}

public override string ToString()
{
return string.Concat(this.FName, ” “, this.LName, ” “, this.Age);
}

public static implicit operator string(ClassA c) // implicit Convert ClassA to string
{
return c.FName + ” ” + c.LName;
}

public static implicit operator byte(ClassA c) // implicit Convert ClassA to byte
{
return c.Age;
}

public static implicit operator int(ClassA c) // implicit Convert ClassA to int
{
return c.Age;
}

public static implicit operator ClassA(string name) // implicit Convert string to ClassA
{
return new ClassA(name, string.Empty, 0);
}

public static implicit operator ClassA(byte age) // implicit Convert age to ClassA
{
return new ClassA(“Anonymous”, string.Empty, age);
}
}

USING:

var c1 = new ClassA(“ROBY”, “COHEN”, 35);
string name = c1;
byte age1 = c1;
int age2 = c1;

Console.WriteLine(name);
Console.WriteLine(age1);
Console.WriteLine(age2);

ClassA c2 = “TEST”;
ClassA c3 = 45;

Console.WriteLine(c2.ToString());
Console.WriteLine(c3.ToString());

Author Avatar

About the Author

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

No Comments


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