deczaloth
deczaloth

Reputation: 7495

How to get name of Field in Field declaration in c#

What i do have:

I am declaring a large number of fields most of which are given its own name as string value. Something like

string ErrorCode0001 = "ErrorCode0001-C";
string ErrorCode0002 = "ErrorCode0002";
string ErrorCode0003 = "ErrorCode0003";
string ErrorCode0004 = "ErrorCode0004";
string ErrorCode0005 = "ErrorCode0005";
string ErrorCode0006 = "ErrorCode0001";

Now, if you put attention in the code above i had a mistake in ErrorCode0006, which is hard to notice.

The mistake above comes because i copy pasted the first Field declaration and then just modified the suffix number, missing the one in the last field.

What i would like to have:

I would love to write something like

string ErrorCode0001 = $"{nameof(self)}-C";
string ErrorCode0002 = $"{nameof(self)}";
string ErrorCode0003 = $"{nameof(self)}";
string ErrorCode0004 = $"{nameof(self)}";
string ErrorCode0005 = $"{nameof(self)}";
string ErrorCode0006 = $"{nameof(self)}";

but i am not sure how to do this in C#.

Would love to see some clever suggestions here.

Upvotes: 1

Views: 366

Answers (1)

deczaloth
deczaloth

Reputation: 7495

One way to achieve this would be to use CallerMemberName attribute.

For this you define a method like:

private static String GetName([CallerMemberName] string fieldName = "")
            => fieldName;

which when called parameterless will return the name of the calling member (the field in your case!).

You use it like:

public static readonly string KPT1_0001 = $"{GetName()}-C";
public static readonly string KPT1_0002 = $"{GetName()}";
public static readonly string KPT1_0003 = $"{GetName()}";
public static readonly string KPT1_0004 = $"{GetName()}";
public static readonly string KPT1_0005 = $"{GetName()}";
public static readonly string KPT1_0006 = $"{GetName()}";

private static String GetName([CallerMemberName] string fieldName = "")
    => fieldName;

Upvotes: 4

Related Questions