I can't find anything on the net that will help me figure this out, if someone could please help you would be a lifesaver.
my function is given a property name and the object. Using reflection it returns the value of that property. It works perfectly however if i pass it a Nullable DateTime it gives me null and no matter what i try i cant get it to work.
public static string GetPropValue(String name, Object obj)
{
Type type = obj.GetType();
System.Reflection.PropertyInfo info = type.GetProperty(name);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
return obj.ToString();
}
in the above function obj is null. How do i get it to read the DateTime?
Your code is fine-- this prints the time of day:
class Program
{
public static string GetPropValue(String name, Object obj)
{
Type type = obj.GetType();
System.Reflection.PropertyInfo info = type.GetProperty(name);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
return obj.ToString();
}
static void Main(string[] args)
{
var dt = GetPropValue("DtProp", new { DtProp = (DateTime?) DateTime.Now});
Console.WriteLine(dt);
}
}
To avoid an exception for a null value, change the last line of GetPropValue to:
return obj == null ? "(null)" : obj.ToString();
This works fine for me..
Are you sure your PropertyInfo is returning a non null ?
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc.CurrentTime = DateTime.Now;
Type t = typeof(MyClass);
PropertyInfo pi= t.GetProperty("CurrentTime");
object temp= pi.GetValue(mc, null);
Console.WriteLine(temp);
Console.ReadLine();
}
}
public class MyClass
{
private DateTime? currentTime;
public DateTime? CurrentTime
{
get { return currentTime; }
set { currentTime = value; }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With