tags:

views:

569

answers:

5

I have a class in C# with a public member. For example:

public class Foo
{
    public int Bar;
}

I'd like to get the FieldInfo for Bar, without having to do:

return this.GetType().GetField("Bar");

I'm just looking for a cleaner, shorter way to do this. Something like:

return field(Bar);

I could, of course, build a method:

public FieldInfo field(string name)
{
     return this.GetType().GetField(name);
}

I was just wondering if C# had something built-in for this sort of code. Something that would check at compile-time, since the above method will cause a run-time error if I misspell the field's name.

Thank you!

+1  A: 

No, what you have is about as clean as it gets.

Andrew Hare
A: 

I am not very sure whether there is a way other than the reflection, which basically exactly serves this purpose.

J.W.
I think morrog was looking for some sort of "compile-time reflection" which isn't (yet, hopefully!) available in C#...
MartinStettner
Yeah, compile-time reflection is probably a better description of what I'm looking for. My two main concerns with the method I posted are safety and performance, more the former than the latter.
morrog
A: 

I also was looking for something like this, because reflection didn't work out well in obfuscated code. I'm afraid there's no better solution... (I ended up with adding custom attributes to all fields and having some code iterating through all fields looking for these attributes, but that's even uglier than your solution).

I hope Microsoft get's this fixed in C#4.0 (I've seen a suggestion for a methodof / propertyof operator in this thread)

MartinStettner
A: 

You can give it a shot with Expressions and Linq. But I cannot provide you with more details on this, sorry.

Rashack
That would be much more complicated than the OQ's solution.
jfar
A: 

See Marc's answer to this question.

ShuggyCoUk
That's an interesting solution. Lengthy, but it is safe. Thank you for the reference.
morrog
I'd give Marc the points if I could :)
ShuggyCoUk