How can I make class, that can be cast to DateTime. But I need to cast my class, when it packed. For example:
object date1 = new MyDateTime();
DateTime date2 = (DateTime)date1;
I need directly this working example.
I know how to do it, but my way will work without packing. I’m not sure is there way to do it.
Please, help.
PS. I need cast directly object to DateTime. So, MyDateTime have to be packed before. Explicit works well, but it doesn’t help if you have packed object. And it have to cast just using ordinary casting like
(DateTime) (object) MyDateTime
What you appear to be after is inheritance, being able to “store” a derived class instance in a variable of the base type like so:
The fact that it is a
FileStreamunder the hood is not lost just because you are pointing to it with theStreamgoggles on.DateTimeis astruct, andstructinheritance is not supported – so this is not possible.An alternative is the
explicitkeyword for user-defined conversions (syntactically looking like casts). This allows you to at least interchange between your class andDateTimewith more sugar.This could look like:
You can do the same with the counterpart
implicitkeyword:That then lets you do the “casting” implicitly:
Another alternative is to wrap
DateTimewith your own adapter class that internally uses aDateTimeand then inherit from this class to createMyDateTime. Then instead of usingDateTimein your code base, you use this adapter class.I’ve seen similar things with
SmartDateTimestyle classes where theDateTimehas a better understanding of nulls and if it was set.