0

I have tried a few methods to obtain a name including investigating PropertyItems and the old fashioned ToString() method to try to obtain the name of an image resource as a string.

I have a selection of images, named, in a resources file. I have no issue getting the image to display using resource.imageName. I would like to try to get imageName as a string to reduce errors and typos elsewhere in my code.

using resource.imageName.ToString() provides me with the string System.Drawing.Bitmap

Adsy2010
  • 525
  • 6
  • 23

2 Answers2

1

You can create a function:

public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
    return (propertyExpression.Body as MemberExpression).Member.Name;
}

And then use it in this way:

public class ClassName {
   public Foo { get; set; }
}
...
...
...
var inst = new ClassName();
var propertyName = GetPropertyName(() => inst.Foo);

It wasn't me who came up with this, I took it from other topic and ran it to see if it works but my browser crashed and I can't find the link to the original topic. I will edit my post as soon as I find it.

Edit: I've found it! This is where I took the snippet from. Good luck.

Edit2: If you are able to get resource.imageName with ease, then just pass it to GetPropertyName function. If not, I guess my answer is incomplete

Community
  • 1
  • 1
Mirza
  • 213
  • 2
  • 8
  • Thank you, that works! Didnt need the classname bit and replaced inst with the resources file instead – Adsy2010 Sep 05 '15 at 22:42
1

In Visual Studio 2015 you can use nameof()

string s = nameof(Resource1.myfile); // s = "myfile"
Jeff
  • 556
  • 3
  • 13