Will
Will

Reputation: 10411

Ambiguity between method/field

Is there any way besides renaming the field to assign it a value if its name is the same as a method?

As of writing this I was just thinking maybe reflection can be used.

Reflection works, but is there a better/different way of doing this?

FieldInfo fi = typeof(TheClass).GetField("TheClash");
fi.SetValue(TheClassObj, TheFieldValue);

Upvotes: 3

Views: 2242

Answers (4)

SquidScareMe
SquidScareMe

Reputation: 3218

You may want to look closer at BindingsFlags, which are optional arguments to Type.GetField(). There is one for GetField and one for GetProperty. Hope this helps!

Upvotes: 1

SquidScareMe
SquidScareMe

Reputation: 3218

Why not cast TheClassObj to type TheClass and access it's property that way?

((TheClass)TheClassObj).TheField = "blah";

Upvotes: 1

codymanix
codymanix

Reputation: 29490

Sure, reflection is the way to access fields or methode by their name. But why do you want to do this?

You can do:

public int Test{get;set;}

The compiler will then generate the variable under the hood for you.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062855

How does it have the same name? That shouldnt (AFAIK) be commonly possible. If the problem is with a base-class, maybe:

base.fieldName = value;

If you mean method vs variable, then:

this.MethodName();

Other than that, the only way I see a problem is it you have "foo" and "Foo", and are calling from a case-insensitive language like VB.

Upvotes: 2

Related Questions