Reputation: 464
I've tried googling this and am also using the search feature on this site, but none of the answers I've found answer my question.
In Visual Basic, if I wanted an easy way to convert from one of my classes to another custom class, I can define the CType
operator to define how to convert from one class to the other. I can then call CType( fromObject, toNewType)
to do the conversion or in C# I guess you can just do a simple cast.
However, in C#, how do you define how the actual cast will be handled from one custom class to another to another custom class (like you can in Visual Basic using the CType
operator)?
Upvotes: 3
Views: 9553
Reputation: 15571
If you do not have any specific code for conversion, System.Convert
methods are closest to CType
in Visual Basic. Otherwise, it can be seen in light of some example like:
VB.NET
Dim btn As Button = CType(obj, Button)
C# Equivalent:
Button btn = (Button)obj
or
Button btn = obj as Button
Upvotes: 0
Reputation: 20357
I think you want the explicit operator
Example from MSDN:
// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Fahrenheit f)
{
return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}
Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;
Upvotes: 2
Reputation: 60902
You could define a custom cast using the explicit keyword:
public static explicit operator TargetClass(SourceClass sc)
{
return new TargetClass(...)
}
...but consider not doing that. It'll confuse the folks who will have to maintain your software down the line. Instead, just define a constructor for your target class, taking an instance of your source class as an argument:
public TargetClass(SourceClass sc)
{
// your conversions
}
Upvotes: 10