0

Let's say I have this method that gets string as a extension parameter:

private static List<string> ValidationErrors = new List<string>();

private static void ErrorCheck<T>(this string str)
{
    if (string.IsNullOrEmpty(str))
    {
        // This just returns "str"                                                                    
        // Instead of property name (see "How I use" section")
        ValidationErrors.Add(typeof(T).Namespace + "[" + nameof(str) + "]");
    }
}

And this is how I use it:

Car.Color.ErrorCheck<Car>();

Where Car object's Color is just string property. So what I want is to get "Color" instead of "str" in my extension method.

Any ideas how I could achieve this?

pavjel
  • 486
  • 10
  • 25
  • 1
    `Car.Color.ErrorCheck()` The fact that you could mismatch types (e.g. `Car.Color.ErrorCheck()`) should clue you in that your current system is flawed. When you pass a string as a parameter, there is no way to know where that string originally came from (`Car.Color` in your case). A much more workable solution (and less prone to developer error) would be something like `Car.ErrorCheck(x => x.Color)` – Flater Aug 03 '17 at 12:07
  • Yeah, thanks! Didn't think of that before your comment. Seems legit. – pavjel Aug 03 '17 at 12:08

1 Answers1

2

No, it's not possible. C# has a few options:

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445