Reputation: 3233
I am trying to teach myself to leverage generic types when creating methods when possible. Is it possible to combine these 2 methods into one method that uses a generic type?
private Decimal? NullDec(string val)
{
return String.IsNullOrEmpty(val) ? (Decimal?)null : Convert.ToDecimal(val);
}
private Int32? NullInt(string val)
{
return String.IsNullOrEmpty(val) ? (Int32?)null : Convert.ToInt32(val);
}
Upvotes: 3
Views: 78
Reputation: 221
I wrote some code for you.
Try to this one
public class NullTest
{
public T Null<T>(string val, Func<string, T> func)
{
return func(val);
}
}
public class TestConvert
{
public int? ConvertToInt32Null(string val)
{
if (string.IsNullOrWhiteSpace(val))
return null;
return Convert.ToInt32(val);
}
public decimal? ConvertToDecimalNull(string val)
{
if (string.IsNullOrWhiteSpace(val))
return null;
return Convert.ToDecimal(val);
}
}
class Program
{
static void Main(string[] args)
{
var test = new NullTest();
var converter = new TestConvert();
int? t1 = test.Null("2", converter.ConvertToInt32Null);
decimal? t2 = test.Null("", converter.ConvertToDecimalNull);
}
}
Upvotes: 0
Reputation: 2226
It is possible to implement something like your methods with Convert.ChangeType()
, but I am not sure it's advisable:
using System;
namespace Example
{
internal class Program
{
public static void Main(string[] args)
{
var @int = Foo<int>("3");
var @double = Foo<double>("3.14");
var dateTime = Foo<DateTime>("01/02/2016");
var @decimal = Foo<decimal>("3.1");
Console.WriteLine($"{@int} is a {@int.GetType()}");
Console.WriteLine($"{@double} is a {@double.GetType()}");
Console.WriteLine($"{dateTime} is a {dateTime.GetType()}");
Console.WriteLine($"{@decimal} is a {@decimal.GetType()}");
Console.ReadLine();
}
public static T? Foo<T>(string val) where T : struct, IConvertible
{
return string.IsNullOrEmpty(val) ? null : Convert.ChangeType(val, typeof(T)) as T?;
}
}
}
Upvotes: 2