3

I have a date-time variable like this:

DateTime myDate=DateTime.Now; // result is like this: 8/2/2020 12:54:07 PM

and I want to get myDate variable like this

DateTime getOnlyDate=myDate.Date; 

and I want to get myDate.Date; with reflection how can I get Date property value with reflection? with reflection I do something like this:

PropertyInfo myDate = typeof(DateTime).GetProperty("Date");

but I don`t know how can I request myDate.Date; value with reflection. thanks in advance

3
  • Add myDate.GetValue(myDate); Commented Aug 2, 2020 at 8:43
  • 1
    @רועיאבידן: That's not going to work as-is, because myDate can't simultaneously be a PropertyInfo and a DateTime. I realize that's a problem in the OP's code, but it would be better not to propagate it into a comment. Commented Aug 2, 2020 at 8:43
  • You are right, didn't noticed he named both with the same name... Commented Aug 2, 2020 at 8:44

1 Answer 1

6

Once you've retrieved the PropertyInfo, you fetch the value with PropertyInfo.GetValue, passing in "the thing you want to get the property from" (or null for a static property).

Here's an example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        DateTime utcNow = DateTime.UtcNow;
        
        PropertyInfo dateProperty = typeof(DateTime).GetProperty("Date");
        PropertyInfo utcNowProperty = typeof(DateTime).GetProperty("UtcNow");
        
        // For instance properties, pass in the instance you want to
        // fetch the value from. (In this case, the DateTime will be boxed.)
        DateTime date = (DateTime) dateProperty.GetValue(utcNow);
        Console.WriteLine($"Date: {date}");
        
        // For static properties, pass in null - there's no instance
        // involved.
        DateTime utcNowFromReflection = (DateTime) utcNowProperty.GetValue(null);
        Console.WriteLine($"Now: {utcNowFromReflection}");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.