I need a generic method that can return a value parsed from a string
public T GetDefaultValue<T>(){
// if typeof(T) is Double it should try to parse some string (supposedly which's been read from DB),
// and return Double value, or if typeof(T) is Int, then it should parse the string
//into Int, and finally if typeof(T) is a string, then no parsing is needed.
}
UPD… Why can’t I check if T is some certain type and use Parse method accordingly?
Convert.ChangeTypecould be used to make your conversions.Notice that to even make this work, you are specifying your types? What’s the savings over using
int.Parse(orTryParse),double.Parse, etc.?And since you mention your inputs are likely coming from a database, and still knowing that to even use the above method you have to specify the type parameter already, I would encourage you to (a) know and trust your types and (b) use existing functionality to obtain values from data sources. No need to convert something to a string and then convert it back to whatever data type you wish it to be.
This also supports if the numeric values could be nullable in the database.