Override / handle my own type conversions in .Net

Possible duplicate:
Is there a way to define an implicit conversion operator in VB.NET?

I don’t remember ever seeing or hearing about anyone doing this; but now I'm in a situation where, in my opinion, it would be incredibly useful to define my own "type conversion" for my class.

As an example, let's say I have my own class, AwesomeDataManager. It does not inherit from a DataTable, but it stores data similarly to a DataTable. I could say: "myDataTable = CType (MyAwesomeDataManager, DataTable)" and make it execute some code inside my class, which will return a populated DataTable.

Of course, I could do something like "MyAwesomeDataManager.GetDataTable", but for the sake of integration with the existing code base, I would like to avoid it.

+4
source share
2 answers

You can use an implicit or explicit conversion, for example: (Note that LetMeChange is implicitly discarded in SomethingMoreComfortable)

class Program { static void Main(string[] args) { LetMeChange original = new LetMeChange { Name = "Bob" }; SomethingMoreComfortable casted = original; Console.WriteLine(casted.Name); } } public class LetMeChange { public static implicit operator SomethingMoreComfortable(LetMeChange original) { return new SomethingMoreComfortable() { Name = original.Name }; } public string Name { get; set; } } public class SomethingMoreComfortable { public string Name { get; set; } } 
+3
source

There are two keywords in C # that help with type conversions: implicit and explicit .

In this case, you will need implicit code for eye candy. However, be careful with this, as this can lead to confusion when people realize what you are doing. I tend to overlook the use of implicit conversions by simply reading the code quickly (obviously hard to miss because they need castes).

+2
source

All Articles