A junior co-worker of mine managed to write very scary, scary code.
printJob.Type = item[LocalFunctions.GetName(new { printJob.Type })].ToString();
public static string GetName<T>(T item) where T : class
{
try
{
return typeof(T).GetProperties()[0].Name;
}
catch (Exception ex)
{
return null;
}
}
What is you gues what will GetName will output? It will output “Type”!
I just don’t get how this is possible. My first thought is that MS will create an anonymous type with property that has the same name as the property from which the value came from (compiler magic?). As this cannot possibly be a supported feature, I advised my junior co-worker to not use things he cannot understand.
But that leaves the question open: How is this possible?
Anonymous types infer property names unless they are specified:
http://msdn.microsoft.com/en-us/library/bb397696.aspx
The compiler then infers the type for the generic at compile time – so
typeof(T)works. It is fully supported, even if the code is fragile. What happens when someone refactors the name of the property?I’d also say it’s inadvisable to advise people on topics you don’t have an answer to yourself – this is the source of many a http://www.thedailywtf.com article 😉
Personally I’d still remove this in favour of more robust code, instead of assuming the property name is always going to be the same.