whenever have local variables in method, resharper suggests convert them constants:
// instead of this: var s = "some string"; var flags = bindingflags.public | bindingflags.instance; // resharper suggest use this: const string s = "some string"; const bindingflags flags = bindingflags.public | bindingflags.instance;
given these constant values (and not variables) understand resharper suggest change them const.
but apart that, there other advantage when using const (e.g. better performance) justifies using const bindingflags
instead of handy , readable var
keyword?
btw: found similar question here: resharper suggesting me make const string instead of string, think more fields of class question local variable/consts.
the compiler throw error if try assign value constant, possibly preventing accidentally changing it.
also, there small performance benefit using constants vs. variables. has way compiled msil, per this msdn magazine q&a:
now, wherever myint referenced in code, instead of having "ldloc.0" value variable, msil loads constant value hardcoded msil. as such, there's small performance , memory advantage using constants. however, in order use them must have value of variable @ compile time, , references constant @ compile time, if they're in different assembly, have substitution made.
constants useful tool if know value @ compile time. if don't, want ensure variable set once, can use readonly keyword in c# (which maps initonly in msil) indicate value of variable can set in constructor; after that, it's error change it. used when field helps determine identity of class, , set equal constructor parameter.
Comments
Post a Comment