Click here to Skip to main content
Click here to Skip to main content

One Type To Convert Them All

By , 5 Jan 2006
 

Introduction

Have you ever wished if there could be a type that could be converted at least to all primitive types?

  • One type to handle strings.
  • One type to handle numerics.
  • One type to handle date & time.
  • One type to convert them all.

I don't know if this is a good behaviour in clean designs or not, but it was interesting to me to do so. In addition, I encountered using dynamic types in many languages, especially in scripting and string processing languages like Python.

I heard about integrating something like dynamic typing in C# 3.0. I think it is a bad news. Because C# will be no more a type-safe programming language. Microsoft plans to import everything to it, and I think that will be a buzz oriented language and will produce product oriented developers. After all, I wrote this. You may use it in scenarios like propagating values to UI.

All of the primitive types - which implements the IConvertible interface - can be converted to this type and vice versa.

Using the code

Using the code is simple. You can include the two files [available in the download file above] in your project and compile them in the whole project.

Notice that there are special situations where the C# compiler can not retrieve the type of the variable. In such cases, just cast the variable to the target type. Here is a small sample code:

Variable v = 100;
string s = v;
s = "10.8";
v = s;
double d = v;

Interesting huh? Just try it and let me know how it was useful (if it happens :) ).

History

There is a long history about dynamic typing and static types vs. dynamic types. But I think these are different areas and respond to solving different problems. Integrating all of the possible features that are used in various languages and solutions will lead us to spaghetti code again. And this time, at a higher level, even in conceptual levels.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Kaveh Shahbazian
Web Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
A .NET Developer came from a 'C' and 'C++' background with some experiences in low level programming. In last 2 years I have performed various works in ASP.NET 2.0, .NET compact framework and other .NET things.
I am looking forward for functional programming to be mainstream (Lisp (Scheme), F#, Erlang and Haskell (Clean)). There are two path there I love them both: Lisp path (Power of macros with Scheme, ...) and ML path(Power of ADT and patterns with F#, Haskell, ...) and there are some middle ground too (Nemerle, Scala).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberNatza Mitzi9 Feb '09 - 12:37 
It is an uninteresting parsing implementation of types and I am all about typed objects.
GeneralNot like Python at all!memberPaddy311813 Aug '07 - 9:53 
What you describe is not how Python does things. Python is strongly typed. Python types objects not the names that refer to them, and strings cannot be automatically read as numbers without explicit conversion.
 
You might be confused by seeing a name (analogous to variable), being able to refer to values of different types at different times, but you would need to know more about Python to realise the difference.
 
Python is comparatively easy to learn. Why not get curious. Smile | :)
 
- Paddy.

GeneralGenericsmemberTodd Morris31 Jul '07 - 4:09 
You should take this article to the next level and show how this could be used to allow a generic converter. For example, DbDataReader. You have something you have to GetInt32 or GetString to specify what you want from the db which results in a lot more code. To be able to GetValue without having to implicitly cast values would be a great advancement. Maybe there is something out there already. Maybe not. I think this is a great article and gets a lot of ideas flying around my head as well as in the community.
 
Thanks again,
Todd
GeneralRe: GenericsmemberKaveh Shahbazian31 Jul '07 - 20:54 
Thanks Todd
I'v developed this to teach programming to some newbies and then : this was a practical approach to solve some problems. Ideas for this (and my another article) came from Ruby. In other article, I hacked around a way to extend existing classes and structs using implicit conversion. And fortunately this is coming with C# 3.
Using this anonymous type could be useful and harmful both! I am waiting to see LINQ in action and how does it put type conversion to work.
I will start again with Orcas and I think there is very interesting to put functional programming approach (in C# 3) into work. There you can have type with more flexible interface. For instance, take a look to expanded String class in Rails, which expands String class by many method for converting currency and other units.
I have an eye on Orcas!
Cheers Smile | :)
 
Kaveh Shahbazian

GeneralMisunderstanding of C# 3.0memberjskeet5 Jan '06 - 21:29 
C# 3.0 will not have dynamic typing. It will have anonymous types, and the "var" keyword (implicitly typed local variables). They're not the same thing at all, and no type safety is lost.
GeneralRe: Misunderstanding of C# 3.0memberKaveh Shahbazian14 Jan '06 - 21:25 
You are right. I have read about it. Thanks
 
Kaveh Shahbazian
QuestionWhy?memberaprenot5 Jan '06 - 12:08 
I dont know about everyone else, but I moved away from scripting languages to avoid things like this. It seems to me that this is just a .NET Variant. I could see it being useful if you wanted to create a .NET based scripting language, but why else would you need this?
AnswerRe: Why?protectorMarc Clifton6 Jan '06 - 2:37 
aprenot wrote:
It seems to me that this is just a .NET Variant.

 
I don't see any reference to this in MSDN anywhere. Got a link? Is this a class, a type? The only thing I found was a VariantType enumeration part of the OleDb.
 
Marc
 
Pensieve

GeneralRe: Why?memberaprenot6 Jan '06 - 5:00 
Marc,
It seems we have a misunderstanding. What I mean is that this class that Kaveh has written is the .NET equivalent of the VBScript/JScript/COM Variant. Such a class does not currently exist in .NET. I wasn't saying that he was duplicating effort, I was saying that strong typing is a nice feature of .NET and that using COM Variants is counter productive. Hence the reason for moving away from scripting languages.
 
However (Kaveh), please don't take this too harshly. The work that you have done here is very intriguing and well done. I just don't think it would be a good idea to use.
 
Aaron
GeneralRe: Why?memberKaveh Shahbazian6 Jan '06 - 18:38 
As I said I agree to your 'I just don't think it would be a good idea to use' idea.
But it was an interesting chalenge for me to see how can I implement it. This happens when I tried to teach C# to very novice peaples. And in my class, these types very helps to explain things step by step. After all one aspect of science is to be acumulative and maybe there be a good use of this. Smile | :)
 
Kaveh Shahbazian
GeneralRe: Why?memberScott S.11 Jan '06 - 9:02 
Marc,
 
The Variant type doesn't exist in .NET, but it did exist in VB, and is used heavily in COM/COM+.
 
Hmmm, having just typed that make me wonder, does that mean there is something buried in Interop services that implements the variant for compatibility with COM? Probably not since I haven't run into it, likely the framework converts the variant to a native type and returns it in object.
 
Hmmm again, object can hold anything ... it just doesn't provide implicit conversions between types. Could you define global/static cast operators to go between object and the native types, and internally do the type checking and conversion as is being done in this article, then just use object instead of Variable?
 
Scott
GeneralRe: Why?memberKaveh Shahbazian13 Jan '06 - 19:14 
1 - Please read the articles first and then go on to distribute comments - If it is not very hard and boring for you >Frown | :(
 
2 - What is the relation between your studied concepts and this article?
If you read it a little more carefully you'll see :
"""All of the primitive types - which implements the IConvertible interface - can be converted to this type and vice versa."""
So this is about:
I.IConvertible types
II.Operator Overloading
III.Implicit conversions
 
3 - Excuse me if you made me sad. But you have already done this. Please read the article first, then examin the code and then share your practices that would be usefull after this steps.
 
ThanksD'Oh! | :doh:
 
Kaveh Shahbazian
GeneralRe: Why?memberScott S.16 Jan '06 - 2:04 
re 1: I read the article in full and completely understand the concepts. If I had found it boring I would not have had anything to say.
 
re 2: I have used these concepts numerous times in a number of different languages over many years. My comments were originaly addressed to Marc Clifton, but I added some interesting thoughts that poped into my head as I typed those comments.
I am quite aware of IConvertable, and the difference between explict and implicit convertions. I coded in C++ for over 10 years before even beginning to use C#.
 
re 3: How can I make you sad by replying to another commentor? I was pasing on information to him and anyone else that reads his comment and wonders the same thing.
Instead of taking constructive comments badly and turning _sad_, why not research what I said a little and possibly use concepts I mention to improve your article. Either by explaining how and why you believe your new class is better than those other possible solutions, or by incorporating some of the concepts.
I never really cared for the Variant type because of the enormous overhead, but every noiw and then could really use something like it that is VERY lightweight.
 
Don't be sad ... be glad! We're all here to learn from each other. Smile | :)
 
Scott
GeneralRe: Why?memberKaveh Shahbazian16 Jan '06 - 22:55 
First of all I am very sorry about my rude behaviour in my writing. I had problems about this article and those were my problems not yours. So I made some teenage-like things.
 
Second I did not know you and even I had that does not means I was going to question your developing abilities.
In fact I must thank you for your attention and I will gladly try to expand my communications especially with good programming men Smile | :)
 
I agree with you about overhead, but recently I had some experiences with python and ruby and a little with java. After these long years I have started to understand what is all this 'open source' things about...If I find myself in a proper posision I will share my experiences but the point is nowadays the enterprise applications are going to be developed in a short time and moor's law is on our side to consum resources more confidently. Only in especial cases - like game developing - this titles still matters. In some few years I see a big change in all aspects of developer's lives.
 
Thanks again Smile | :)
 
Kaveh Shahbazian
GeneralNiceprotectorMarc Clifton5 Jan '06 - 11:17 
A very useful class for me, because I'm often dealing with boxed value types.
 
A few questions:
 
What happens if the conversion loses precision, like converting a double to an int?
Can hooks be put in that allow extending the type converter without affecting the original class?
How about some unit tests? Smile | :)
 
Marc
 
Pensieve

GeneralRe: NicememberKaveh Shahbazian6 Jan '06 - 18:42 
When conversion loses precision, is exactly as .NET framework handle it. By now I have not implemented a seperate class for handling numeric types. So you will loose precision as much as .NET do it. As you see internally I used the same conversions as the .NET does. I hope that it will be usefull for you. Smile | :) .
 
Kaveh Shahbazian

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 5 Jan 2006
Article Copyright 2006 by Kaveh Shahbazian
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid