Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any generic Parse() function that will convert a string to any type using parse?

I want to convert a string to a generic type like int or date or long based on the generic return type.

Basically a function like Parse<T>(String) that returns an item of type T.

For example if a int was passed the function should do int.parse internally.

like image 840
Karim Avatar asked Aug 17 '10 12:08

Karim


People also ask

Is parsing the same as casting?

Casting does not create a new object, It will only assign a reference of one datatype to reference of another datatype, only if its assignable. Parsing : Parsing, on the other side, is converting from one data type to another, like from string to int for example. This Creates a new Object, and returns reference to it.

What is parse in C# example?

Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent. Syntax: public static int Parse (string str); Here, str is a string that contains a number to convert.

What is parse in asp net?

Parse strings in . A parsing operation converts a string that represents a . NET base type into that base type. For example, a parsing operation is used to convert a string to a floating-point number or to a date-and-time value. The method most commonly used to perform a parsing operation is the Parse method.


1 Answers

System.Convert.ChangeType

As per your example, you could do:

int i = (int)Convert.ChangeType("123", typeof(int)); DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime)); 

To satisfy your "generic return type" requirement, you could write your own extension method:

public static T ChangeType<T>(this object obj) {     return (T)Convert.ChangeType(obj, typeof(T)); } 

This will allow you to do:

int i = "123".ChangeType<int>(); 
like image 177
Ani Avatar answered Sep 18 '22 21:09

Ani