in writing short helper functions, find myself wanting use variable identifier "value" argument. seems though visual studio compiles fine, , has no complaints, when this:
public void mymethod(int value, bool option, string message) { value = 1; // more code... } however, visual studio complains @ following (as expected):
private int _myproperty; public int myproperty { { return _myproperty; } set { int value = 0; _myproperty = value; } } this leads me believe "value" treated keyword (or not) depending on context. new c# and, far know, have not seen context-specific keywords in other languages.
the question: safe use "value" variable name outside of property setter? if not, when can done safely? and, considered bad practice?
i surprised wasn't able find question asked on so, , suspect has asked before. however, difficult search because many posts have "variable" , "identifier" in title. unable find information on msdn.
edit: last question meant ask if often or commonly frowned upon. has been changed reflect this.
here's msdn says:
the set accessor resembles method return type void. uses implicit parameter called value, type type of property.
the properties syntactic sugar avoids having write lot of get_bar , set_bar methods (note: there other advantages too, clr knows it's property). example, if have class this:
public class foo { private int _bar; public int bar { { return _bar; } set { _bar = value; } } } it'll generate il (for setter) looks this:
.method public hidebysig specialname instance void set_bar(int32 'value') cil managed { // .maxstack 8 il_0000: nop il_0001: ldarg.0 il_0002: ldarg.1 il_0003: stfld int32 program/foo::_bar il_0008: ret } // end of method foo::set_bar the thing note here set_bar method takes parameter called value. not "resemble" method return type void parameter called value, that.
so can't use value else in setter, obviously.
now should use elsewhere? depends. if it's obvious it's referring in context using sure. if value ambiguous in particular context use more explicit.
from msdn:
the contextual keyword value used in set accessor in ordinary property declarations.
it makes no mention of other context value considered keyword, aside setter, or anywhere else might have been defined already, should fine using value. bad practice? not rule, no more other potentially ambiguous variable name.
edit: 1 place think having value name problematic field (or worse property) in class. example:
public class foo { private int value; public int value { { return value; } set { value = value; } // `value` setting? , what? } } now remove ambiguity here this.value = value, still ugly , seems better me use different name field.
Comments
Post a Comment