0

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?

3
  • It does seem like a strange question. What is the intended use? Commented Oct 30, 2009 at 11:56
  • presumably for debug so he can print what method an event is occuring in? Commented Oct 30, 2009 at 11:59
  • from c#6, you can use nameof keyword to obtain the simple (unqualified) string name of a variable, type, or member (learn.microsoft.com/en-us/dotnet/csharp/language-reference/…) Commented Sep 18, 2018 at 14:42

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Well, isn't that what obfuscators are for? :-)
Johannes: Probably ;) But you don't want them to make your code throw an IndexOutOfRangeException.
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.
You don't need an obfuscator to potentially screw this up. The JIT might also do it for you by inlining.
1

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.

1 Comment

dazzler ;-) +1 very interesting approach, never heard of this
0

from C# 6, you can use nameof attribute to print the name of property or method name.

switch (e.PropertyName)
{
    case nameof(YourProperty):
    { break; }

    // instead of
    case "YourProperty":
    { break; }
}

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof

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.