DevTeamExpress
DevTeamExpress

Reputation: 183

C# Reflection DateTime?

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?

Upvotes: 3

Views: 7248

Answers (3)

Rich S
Rich S

Reputation: 3453

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; }
    }
}

Upvotes: 1

Andomar
Andomar

Reputation: 238166

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();

Upvotes: 2

Mattias Buelens
Mattias Buelens

Reputation: 20179

A nullable type is of the type Nullable<T> and has two properties: HasValue and Value. You first need to check HasValue to check if Value is set, then you can access the actual data from Value.

Either you check whether the given object is a Nullable<T> and do these checks in your GetPropValue, or you do this logic outside of this method and make sure you invoke it with a non-nullable value.

EDIT Scratch that, according to MSDN GetType() always gives you the underlying type. Are you sure you're passing a non-null object?

Upvotes: 0

Related Questions