The basic goal is to write a function as such:
int myInt = 5;
PrettyPrint(myVar);
//in some helper class
public static void PrettyPrint<T>(T var) {
Console.WriteLine(/* ??? */ + ": " + var); //output: "myInt: 5"
}
I know we can do nameof(myVar)
inline which would return "myVar"
, however, is it possible to abstract that into a function that lives somewhere else? If we do nameof
in PrettyPrint, in this case it would return "var"
and not the original name.
Now, I know you're thinking "just pass in a string for the name", but ultimately I'd like the following:
public static void PrettyPrintMany<T>(params T[] vars) {
string s = "";
foreach (T v in vars) {
s += <original name> + ": " + t + " | ";
}
Console.WriteLine(s);
}
int myInt = 5;
string myStr = cheese;
float myFloat = 3.14f;
PrettyPrintMany(v1, v2, v3); //"myInt: 5 | myStr: cheese | myFloat: 3.14 | "
I feel like this is not possible, but maybe there is some clever hackery that can be done?