Data loss handling when using user-defined conversion. C#

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?

Answers


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.


You're effectively doing what I'd call an upcast, but without the regular inheritance model (as a regular upcast would be B extends A). Upcasts can lead to data being narrower in scope. If you upcast to a less featured class then you expect that you will have less information, that's just how it works. You don't care about mystring if you're using class A as class a has no mystring.


Need Your Help

PhpStorm - How to detect PHP error "Non-static method should not be called statically"?

php phpstorm code-inspection phpmd phpcodesniffer

With PHP, static method can be used in both static method and non-static method, and non-static method can only used in non-static method. That's why calling a dynamic method statically generates the

factory boy: define field that depends on other field

django django-testing django-tests factory-boy

How to define a field that depends on other field using factory-boy?