How to refer to an identifier without writing it into a string literal in C#? -
i want this:
public void foo(bar arg) { throw new argumentexception("argument incompatible " + name(foo)); }
because if change name of foo ide refactor error message too, won't happen if put name of method (or other kind of member identifier) inside string literal. way know of implementing "name" using reflection, think performance loss outweighs mantainability gain , won't cover kinds of identifiers.
the value of expression between parenthesis computed @ compile time (like typeof) , optimized become 1 string literal changing language specification. think worthy feature?
ps: first example made question related exceptions, not. think of every situation may want reference type member identifier. you'll have through string literal, right?
another example:
[runtimeacessibledocumentation(description="the class " + name(baz) + " job. see method " + name(doitsjob) + " more info.")] public class baz { [runtimeacessibledocumentation(description="this method pretend " + "doing job if argument " + name(doitsjob.arguments.justpretend) + " true.")] public void doitsjob(bool justpretend) { if (justpretend) logger.log(name(justpretend) + "was true. nothing done."); } }
update: question posted before c# 6, may still relevant using previous versions of language. if using c# 6 check out nameof
operator, pretty same thing name
operator in examples above.
well, cheat , use like:
public static string callername([callermembername]string callername = null) { return callername; }
and:
public void foo(bar arg) { throw new argumentexception("argument incompatible " + callername()); }
here, work done compiler (at compile-time), if rename method return correct thing.
Comments
Post a Comment