0
public class Faranheit 
{
    public float Digree { get; set; }

    public Faranheit(float f) 
    {
        Digree = f;
    }

    public static implicit operator Celcius(Faranheit f)
    {
        return new Celcius((5.0f / 9.0f) * (f.Digree - 32));
    }

    public static implicit operator Faranheit(Celcius c)
    {
        return new Faranheit((9.0f / 5.0f) * c.Digree + 32);
    }
}

public class Celcius
{
    public float Digree{get;set;}

    public Celcius(float c)
    {
        Digree = c;
    }

}

I am just confused, where to put the conversion methods exactly..

It works fine even if I put one method in one class and other in the other, or I interchange them or even if I put both of them in any of the two classes..

But if I put it outside these two classes it doesn't work (compile error)..

Could please someone put some light on this..

EDIT:

if it allows the conversion methods to be in either of the class, why doesn't it allow the conversion method to be in a separate class??

techBeginner
  • 3,792
  • 11
  • 43
  • 59

2 Answers2

2

All that matters is that the implicit conversion exists in one of the two classes. I would tend to put both conversions in the less-commonly used class.

In this case, the classes look equal, so I would put the conversion to the class in each class i.e. the conversion from F to C would go in the Celsius class, and vice versa.

Really, it's mostly about personal preference.

In this specific case, I would write a Temperature class that lets you get the temperature in C, F, K, R, etc. But that isn't exactly relevant to the actual question.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • My question actually is, if it allows the conversion methods to be in either of the class, why doesn't it allow the conversion method to be in a separate class?? – techBeginner May 15 '12 at 06:42
-1

I would put them in each of the classes. So you can do stuff like:

Celsius c = new Celsius(Value);
Fahrenheit f = c.toFahrenheit();
Celsius newC = f.toCelsius();

edit: or if you wanted to go the Helper class route, you could do:

public static class ConvertTemps
{
    public static Celsius toCelsius(Fahrenheit F)
    {
        return new Celsius(5/8* F - 32);
    }
    public static Fahrenheit toFahrenheit(Celsius C)
    {
        return new Fahrenheit(8/5*C + 32);
    }
}

and then you could do things like:

Celsius c = new Celsius(value);
Fahrenheit f = ConvertTemps.toFahrenheit(c);

But I'd go the first route.

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67
  • Ah, I overlooked that. Good point. Guess that's a pretty important one. Well, given that, you definitely want one in each class. – Phillip Schmidt May 14 '12 at 17:16