Reputation: 46740
I have a generic method.
private T Blah<T>()
In this method I have a string that I want to return, but the problem is that T
may not be a string. The values T
can be are string
, int
, DateTime
, DateTime?
and decimal?
.
What do I do to this string so that I can return it and support all these types?
Upvotes: 0
Views: 82
Reputation: 4693
I made Blah<T>
public for test, modify it as your requirement.
Code
partial class SomeClass {
public T Blah<T>() {
var t="2013 03 30";
return (T)(typeof(String).Equals(typeof(T))?t as object:(
from args in new[] { new object[] { t, default(T) } }
let type=Nullable.GetUnderlyingType(typeof(T))??typeof(T)
let types=new[] { typeof(String), type.MakeByRefType() }
let bindingAttr=BindingFlags.Public|BindingFlags.Static
let tryParse=type.GetMethod("TryParse", bindingAttr, default(Binder), types, null)
let b=typeof(DateTime)!=type
let dummy=b?args[0]=((String)args[0]).Split('\x20').Aggregate(String.Concat):""
let success=null!=tryParse?tryParse.Invoke(typeof(T), args):false
select args.Last()).Last());
}
}
partial class TestClass {
public static void TestMethod() {
var x=new SomeClass();
Console.WriteLine("x.Blah<String>() = {0}", x.Blah<String>());
Console.WriteLine("x.Blah<int>() = {0}", x.Blah<int>());
Console.WriteLine("x.Blah<DateTime>() = {0}", x.Blah<DateTime>());
Console.WriteLine("x.Blah<DateTime?>() = {0}", x.Blah<DateTime?>());
Console.WriteLine("x.Blah<decimal?>() = {0}", x.Blah<decimal?>());
}
}
Output
x.Blah<String>() = 2013 03 30 x.Blah<int>() = 20130330 x.Blah<DateTime>() = 2013/3/30 0:00:00 x.Blah<DateTime?>() = 2013/3/30 0:00:00 x.Blah<decimal?>() = 20130330
The special thing is that I removed the spaces if destination type is not DateTime
or DateTime?
.
You can even try with x.Blah<long>()
which is not in your requirement, and any other types. Let me know if you found any type can cause an exception.
Upvotes: 1
Reputation: 32481
This may help:
private T Blah<T>(Func<string, T> map)
{
//Your codes here
return map(yourString); //yourString: the string which you are going to convert
}
Here you call it:
//For int
Blah(input => int.Parse(input));
//For DateTime
Blah(input => DateTime.Parse(input));
Upvotes: 1
Reputation: 3526
private T Blah<T> () where T : IConvertible
{
if (!String.IsNullOrEmpty(source))
return (T)Convert.ChangeType(source, typeof(T));
return default(T);
}
Should work for all those types.
Upvotes: 4