How to auto-convert types?

G

Guest

Well, I'm programming in vb.net and I'm developing a custom class (named
XmlEl) that inherits from the XmlElement class. It has a New routine that
receives an xmlelement and constructs the XmlEl instance. But in certain
occasions I need the machine to auto-convert an xmlelement to an xmlel,
rather than having to type all the time New XmlEl(XmlElement). As I've
noticed the CType function exists for that cause. For example, to convert an
xmlnode to a xmlelement, one could use Ctype(XmlNode, XmlElement). That's how
I want to use my class: CType(XmlElelement, XmlEl). So, how can I achieve it?
I also noticed in the SDK the class TypeConverter but I just don't know how
to use/apply it on my class. Any ideas or tips??
 
S

sadhu

In C#, you can provide a conversion operator from your type to the type
you want.
class MyClass
{
public static explicit operator MyDifferentClass(MyClass c)
{
// convert and return an instance of MyDifferentClass
}
}

Calling code can then do
MyClass c = new MyClass();
MyDifferentClass d = (MyDifferentClass) c;

Regards
Senthil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top