tags:

views:

97

answers:

2

This might seam like a strange question but....

public string MyProperty
{
    get
    {
        return "MyProperty";
    }
}

How can I replace the return statement go it returns the property name without it being hard coded?

+9  A: 

I wouldn't recommend doing this in general but here we go:

return MethodBase.GetCurrentMethod().Name.Substring(4);

Using an obfuscator can totally screw this up, by the way.

Mehrdad Afshari
Well, isn't that what obfuscators are for? :-)
Joey
Johannes: Probably ;) But you don't want them to make your code throw an `IndexOutOfRangeException`.
Mehrdad Afshari
thanks :) that worked perfectly. Some further explanation on why I need this: I was given an application that uses about 50 keys from a webconfig file. And my task is to allow the application to work with any number of clients (needing to replicate these 50 keys for each new client). So, I have moved the keys into a separated file and needed to create a class that encapsulates the data access in order to be able to create an array of clients.
Sergio
Sergio: I'd write a simple code generator instead.
Mehrdad Afshari
You don't need an obfuscator to potentially screw this up. The JIT might also do it for you by inlining.
LukeH
+1  A: 

If you're using .NET, you can also use LINQ to identify this:

public static string GetName<T>(Func<T> expr)
{
  var il = expr.Method.GetMethodBody().GetILAsByteArray();
  return expr.Target.GetType().Module.ResolveField(BitConverter.ToInt32(il, 2)).Name; 
}

I can't claim credit for this solution - this came from here.

Pete OHanlon
dazzler ;-)+1 very interesting approach, never heard of this
Marc Wittke