The best way to use a property to reference a Key-Value pair in a dictionary

This is a pretty trivial question, but I'm curious to hear the opinions of people on it.

If I have a dictionary that can be accessed through properties, which of these formats do you prefer for the property?

/// <summary>
/// This class FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
    get {
        return Dictionary["myKey"];
    }
    set {
        Dictionary["myKey"] = value;
    }

This is probably the typical way to do this. It is quite effective, easy to understand, etc. The only drawback is a longer or more complex key, which could seal or change only one instance or something else, which will lead me to this:

/// <summary>
/// This class SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
    get {
        return Dictionary[DICT_MYKEY];
    }
    set {
        Dictionary[DICT_MYKEY] = value;
    }

, , , , "Code Complete". , , /// [DefaultValue()] , .

, , ? - ?

+3
7

, / - . , , . , ,

+4

@Glenn . - , . 10 ( ). , ( , ). , - , .

.:) ! .

+1

, , "DefaultValue" , . .

. MSDN .

0

, , , "", , , . . "Code Complete", . . 2 , "myKey", getter setter, .

.

0

, .

public string FirstProperty {
get {
    return Dictionary[PropertyName()];
}
set {
    Dictionary[PropertyName()] = value;
}

private string PropertyName()
{
    return new StackFrame(1).GetMethod().Name.Substring(4);
}

, , visual studio , .

0

, , , .
- , const.

0

@Joel, StackFrame. , .

: .

0

Source: https://habr.com/ru/post/1696680/


All Articles