0

Im currently struggling to find a solution to an exercise. How can i modify ClassA so that the explicit typeconversion in the second part is possible?

class ClassA {
public int MyValue = 0;
public string MyText = "Hello World!";

//Code to impl
}

ClassA myObject = new ClassA();
myObject.MyValue = 42;
myObject.MyText = "Hi!"
int x = (int)myObject;
string str = (string)myObject;
DJ MERKEL
  • 87
  • 8

2 Answers2

-1

Something like this in your ClassA definition should work:

public static explicit operator int(ClassA a)
{
    return a.MyValue;
}

public static explicit operator string(ClassA a)
{
    return a.MyText;
}

(I actually can't remember if this case would require implicit or explicit, and can't test it at the moment. It's worth testing both for your needs.)

Though it's a little strange why you'd want to do that, instead of just grabbing these public values directly:

int x = myObject.MyValue;
string str = myObject.MyText;
David
  • 208,112
  • 36
  • 198
  • 279
  • thank you, thats what i missed – DJ MERKEL Feb 21 '16 at 19:05
  • @David Not sure why you edited your answer; OP was asking for *explicit* conversion, so the original solution was fine. – poke Feb 21 '16 at 19:06
  • @poke: I was wavering back and forth between the two, actually. It's been a *long* time since I've done this, so I wasn't sure which. – David Feb 21 '16 at 19:07
-2

You define an explicit conversion.

The trick here is the EXPLICIT keywork.

https://msdn.microsoft.com/en-us/library/xhbhezf4.aspx

has examples of that.

Basically: the class must implement a stateic explicit operator in the for like...

// Must be defined inside a class called Fahrenheit:
public static explicit operator Celsius(Fahrenheit fahr)
{
    return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
}
TomTom
  • 61,059
  • 10
  • 88
  • 148