What is the c-sharp equivalent of vb.net CType?

I tried searching on Google, and also using the search function on this site, but none of the answers I found answered my question.

In vb, if you need an easy way to convert from one of my classes to another custom class, I can define an operator CTypeto determine how to convert from one class to another. Then I can call CType( fromObject, toNewType)for conversion or in C #, I think you can just do a simple translation.

However, in C #, how do you determine how the actual selection will be processed from one custom class to another to another custom class (for example, you can use vb with an operator CType).

+3
source share
4 answers

You can define a custom listing using the explicit keyword :

public static explicit operator TargetClass(SourceClass sc)
{
    return new TargetClass(...)
}

... but do not do this. This will confuse people who will have to support your software on 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
}
+9
source

I think you want an explicit statement

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;
+2
source

What you want to do is to overload the translation operators in the class.

+1
source

Unless you have special code to convert, the methods System.Convertare closest to CTypein VB. Otherwise, this can be seen in the light of some example, for example:

Vb.net

Dim btn As Button = CType(obj,Button)

C # Equivalent:

Button btn = (Button)obj or Button btn = obj as Button

0
source

All Articles