Getting Property Name in C#
<p>I have a validation class, and within this I want to verify various properties received form a web service are valid, and report a descriptive error message if not.</p>

<p>Currently the webservice returns all strings, and I want to convert/validate these into more useful types. The problem is I am currently passing the property name through as a string parameter in the method call. Is there a way to get the name of a property for display in the error message without passing it through as a string?</p>

<pre><code>public class WebserviceAccess
{
    public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
    {
        var usefulData = new MyUsefulDataObject();

        usefulData.LastUpdated = webserviceResponse.LastUpdated.IsValidDateTime("LastUpdated");
        // etc . . .
        // But I don't want to have to pass "LastUpdated" through.
        // I'd like IsValidDateTime to work out the name of the property when required (in the error message).

        return usefulData ;
    }
}

public static class WebServiceValidator
{
    public static DateTime IsValidDateTime(this string propertyValue, string propertyName)
    {
        DateTime convertedDate;

        if (!DateTime.TryParse(propertyValue, out convertedDate))
        {
            throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
        }

        return convertedDate;
    }
}
</code></pre>

<p>Any assistance is much appreciated.</p>

<p>Thanks in advance.</p>

<p>EDIT: Using Oblivion2000's suggestion, I now have the following:</p>

<pre><code>public class Nameof&lt;T&gt;
{
    public static string Property&lt;TProp&gt;(Expression&lt;Func&lt;T, TProp&gt;&gt; expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            throw new ArgumentException("'expression' should be a member expression");
        }

        return body.Member.Name;
    }
}

public class WebserviceAccess
{
    public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
    {
        var usefulData = new MyUsefulDataObject();

        usefulData.LastUpdated = Nameof&lt;WebserviceResponse&gt;.Property(e =&gt; e.LastUpdated).IsValidDateTime(webserviceResponse.LastUpdated);
        // etc . . .

        return usefulData ;
    }
}

public static class WebServiceValidator
{
    public static DateTime IsValidDateTime(this string propertyName, string propertyValue)
    {
        DateTime convertedDate;

        if (!DateTime.TryParse(propertyValue, out convertedDate))
        {
            throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
        }

        return convertedDate;
    }
}
</code></pre>
