For educational purposes I do lots of things (that maybe never used) with casting. One of them lead me to solution that I dislike.
Let’s say, I have 2 classes:
class ClassA
{
public int MyInt;
public string MyString;
}
class ClassB
{
public int SomeInt;
}
Now I want implicitly cast ClassA to ClassB. To do that I can write:
public static implicit operator ClassB(ClassA obj1)
{
ClassB obj2 = new ClassB();
obj2.SomeInt = obj1.MyInt;
return obj2;
}
But there’s a possibility that MyString get lost, that must not be allowed. To solve this problem I’ve added to my conversion:
if (obj1.MyString != null)
throw new DataLostException();
This works fine, but there must be simpler solution. My question is, How can I handle this kind of data loss in a simpler way?
Your solution is correct. Such data loss is the “default behavior” when creating a user defined conversion operator, which is a relatively advanced use of the language.
There is no inheritance relation between the two classes, and there is no way for the framework to know how that string might relate to the other class. Who knows, it might be a piece of diagnostic information that is completely unnecessary in the new context.