A coworker and myself where discussing conversion in .NET he pointed out there are four ways to convert a type, at first I could only come up with two, implicit and explicit then he pointed out user defined conversions and using helper classes so I decided to look it up here http://msdn.microsoft.com/en-us/library/ms173105.aspx while reading that it dawned on me that I do a lot of WPF and often times use the IValueConverter interface.
My Question started as – isn’t IValueConverter just an example of a conversion with a helper class (when you implement it of course)? Then I was like well, what is the real difference between user-defined conversions and conversions with a helper class? If you follow the links from the above mentioned MSDN page the documentation is sorda slim. Like this is the example from the conversion operators page.
class SampleClass
{
public static explicit operator SampleClass(int i)
{
SampleClass temp = new SampleClass();
// code to convert from int to SampleClass...
return temp;
}
}
It doesn’t really make it so clear. To me it looks like a static class that needs an int in the ctor?
Anyway – Hopefully some C# ninja can illuminate this subject. One final thought is, I generally try and stay away from converting things unless there is a real good reason (i.e. parsing a spreadsheet) in regular everyday code I tend to think of it as a code smell, is that considered best practice?
Thanks
This isn’t a full answer to your questions, but that code snippet overrides the “explicit cast” of the class, which isn’t really intuitive fromt eh method signature. Basically it would allow you to do:
Common sense says that cast should fail, because and
intisn’t aSampleClassbut the code snippet in your question comes into play, and makes the cast possible.The other complementing method is:
Note the keyword here is
implicitinstead ofexplicit, and this version would allow for implicit casting, so this would work:Note that you no longer have to specify the cast.