Reputation: 77
There are problems occurred while understanding type casting in C#. I created a simple class and overloaded the ToString()
method for it, so that the values of the class object fields are output in a string:
public class Triple{
public int Int32;
public string String;
public bool Boolean;
public Triple(int Int32, string String, bool Boolean)
{
this.Int32 = Int32;
this.String = String;
this.Boolean = Boolean;
}
public override string ToString()
{
return String.Format("{0},{1},{2}", this.Int32, this.String, this.Boolean);
}
I also set an implicit conversion of an object of the Triple class to the bool type:
public static implicit operator bool(Triple T1)
{
if (T1.Boolean)
{
return true;
}
else
{
return false;
}
}
Now when I call:
Triple t1 = new Triple(1, "abcd", true);
Console.WriteLine(t1);
The Boolean field of the Triple class is shows as output, not the value of the class fields.
Why is this happening?
Upvotes: 4
Views: 1642
Reputation: 1271
Well, it's because you added an implicit operator. The implicit keyword provides conversion functionality. An implicit conversion involves casting from one type to another. With the implicit keyword, you implement the casting functionality as an operator method for operator overloading.
Link: See this MS Doc for further explanations
Upvotes: 0
Reputation: 1062780
There are overloads of Console.WriteLine
that take bool
and object
(among others). The compiler is preferring bool
because you have an implicit conversion operator. You could add a (object)
or .ToString()
, but honestly, I'd probably lose the operator - not sure it is helping you any here.
Upvotes: 6