Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection DateTime?

Tags:

c#

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?

like image 413
DevTeamExpress Avatar asked Sep 07 '26 16:09

DevTeamExpress


2 Answers

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();
like image 136
Andomar Avatar answered Sep 10 '26 07:09

Andomar


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; }
    }
}
like image 41
Rich S Avatar answered Sep 10 '26 07:09

Rich S