Faster way to convert from a String to generic type T when T is a valuetype?
Posted
by
Kumba
on Stack Overflow
See other posts from Stack Overflow
or by Kumba
Published on 2011-01-06T04:58:53Z
Indexed on
2011/01/09
0:53 UTC
Read the original article
Hit count: 171
vb.net
Does anyone know of a fast way in VB to go from a string to a generic type T
constrained to a valuetype (Of T as Structure
), when I know that T
will always be some number type?
This is too slow for my taste:
Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T)
But it seems to be the only sane method of getting from a String
--> T
. I've tried using Reflector to see how Convert.ChangeType
works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T
so it can be returned.
I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T)
value. If I strongly-type my class for a specific number type (i.e., UInt16
), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use.
It'd almost be nice if there was converter to/from T
while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?
© Stack Overflow or respective owner