How to convert from decimal to T?

I created a wrapper over the NumbericUpDown control. Wrapper is generic and can support int? and double?

I would like to write a method that will do the following.

public partial class NullableNumericUpDown<T> : UserControl where T : struct { private NumbericUpDown numericUpDown; private T? Getvalue() { T? value = numericUpDown.Value as T?; // <-- this is null :) thus my question return value; }} 

Of course, there is no fill between the decimal and double comma? or int? so i need to use a specific conversion method. I would like to avoid switching or expressions.

What would you do?

To clarify my question, I provided more code ...

+4
source share
3 answers

It’s not clear how you are going to use it. If you want double to create the GetDouble () method, for integers GetInteger ()

EDIT:

Ok now i think i understand your use case

Try the following:

 using System; using System.ComponentModel; static Nullable<T> ConvertFromString<T>(string value) where T:struct { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null && !string.IsNullOrEmpty(value)) { try { return (T)converter.ConvertFrom(value); } catch (Exception e) // Unfortunately Converter throws general Exception { return null; } } return null; } ... double? @double = ConvertFromString<double>("1.23"); Console.WriteLine(@double); // prints 1.23 int? @int = ConvertFromString<int>("100"); Console.WriteLine(@int); // prints 100 long? @long = ConvertFromString<int>("1.1"); Console.WriteLine(@long.HasValue); // prints False 
+5
source

Since this method will always return a result

 numericUpDown.Value 

you have no reason to convert the value to any value other than decimal. Are you trying to solve a problem that you do not have?

0
source
 public class FromDecimal<T> where T : struct, IConvertible { public T GetFromDecimal(decimal Source) { T myValue = default(T); myValue = (T) Convert.ChangeType(Source, myValue.GetTypeCode()); return myValue; } } public class FromDecimalTestClass { public void TestMethod() { decimal a = 1.1m; var Inter = new FromDecimal<int>(); int x = Inter.GetFromDecimal(a); int? y = Inter.GetFromDecimal(a); Console.WriteLine("{0} {1}", x, y); var Doubler = new FromDecimal<double>(); double dx = Doubler.GetFromDecimal(a); double? dy = Doubler.GetFromDecimal(a); Console.WriteLine("{0} {1}", dx, dy); } } 

 private T? Getvalue() { T? value = null; if (this.HasValue) value = new FromDecimal<T>().GetFromDecimal(NumericUpDown); return value; } 
0
source

Source: https://habr.com/ru/post/1276984/


All Articles