Question

I really enjoyed this article, Make the Type System Do the Work by Nathan Wong, but it's hard for me to follow the code examples because I'm not familiar with C++. How would you write this C++ code in VB.NET or C#?

struct Degrees
{
    double val;
    Degrees(double _val) : val(_val) {}
};
struct DegCelsius : public Degrees
{
    DegCelsius(double deg) : Degrees(deg) {}
    DegCelsius(const DegFahrenheit &deg)
        : Degrees((deg.val - 32) * 5 / 9) {}
};
struct DegFahrenheit : public Degrees
{
    DegFahrenheit(double deg) : Degrees(deg) {}
    DegFahrenheit(const DegCelsius &deg)
        : Degrees(deg.val * 9 / 5 + 32) {}
};

DegFahrenheit input(68);
DegCelsius temperature = input;
Was it helpful?

Solution

I assume this could be improved some how. VB.NET version:

Public MustInherit Class Degrees
  Public Property val As Decimal
End Class
Public Class DegFahrenheit
  Inherits Degrees
  Public Sub New(ByVal deg As Decimal)
    Me.val = deg
  End Sub
  Public Sub New(ByVal degCel As DegCelsius)
    Me.val = degCel.val * 9 / 5 + 32
  End Sub
  Public Shared Widening Operator CType(ByVal Celsius As DegCelsius) As DegFahrenheit
    Return New DegFahrenheit(Celsius)
  End Operator
End Class
Public Class DegCelsius
  Inherits Degrees
  Public Sub New(ByVal deg As Decimal)
    Me.val = deg
  End Sub
  Public Sub New(ByVal fahrenheit As DegFahrenheit)
    Me.val = (fahrenheit.val - 32) * 5 / 9
  End Sub
  Public Shared Widening Operator CType(ByVal Farenheit As DegFahrenheit) As DegCelsius
    Return New DegCelsius(Farenheit)
  End Operator
End Class

For Testing:

Dim Input = New DegFahrenheit(68) 'Val = 68
Dim Celsius As DegCelsius = Input 'Val = 20
Dim Fahrenheit As DegFahrenheit = Celsius 'Val = 68

And as an unnecessary addition, which I would want for debugging add this to the Degrees class so that the value will display in the locals with no need to expand:

Public Overrides Function ToString() As String
  Return val
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top