I have an input string such as
"x=y|a=b|c=10" etc
which gets converted to dynamic which i use as
dynamic d = getDynamicFromStringAbove();
someFunc( d.a.AsType<int>() )
where AsType is an extension method defined as
public static T AsType<T>(this string o){
return (T) Convert.ChangeType(o, typeof(T));
}
QUESTION – Is there anything in the framework which provides this already
object.AsType<T>()
?? It seems pretty handy with dynamic types so i am guessing it’s there and i don’t want to add code which already exists
No, there’s no built-in method that works like your extension method. I think the framework designers wanted people to know that an explicit operation has to be performed to parse a string to an int, etc.
BTW, might I suggest changing your
AsTypemethod to use aTypeConverterinstead ofConvert.ChangeType? It’s a little more powerful and flexible. For example, it works better for converting enum values to their respective types.See this answer for more info.
Update
I should point out:
.AsType()method takes anobjectas its parameter. As it stands in the question you are taking astring, and in what way iss.AsType<int>()preferable toint.Parse(s)?dynamicvalue, the code provided in the question won’t actually work without castingd.ato a string value.