Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a field has 'new' modifier via reflection? [duplicate]

Tags:

c#

reflection

Possible Duplicate:
How do I detect the "new" modifer on a field using reflection?

Having the following declaration

public class B : A
{
    public new string Name;
}

how do i determine if the field has 'new' modifier for its FieldInfo instance?

like image 877
UserControl Avatar asked Aug 31 '11 12:08

UserControl


2 Answers

For fields, no such exists; the IL is simply:

.field public string Name

etc - since there is no concept of virtual fields or newslot etc. The new modifier here exists purely for the compiler, for you to assert that you acknowledge you are doing something a little bit confusing. Adding the new here will suppress a compiler warning (CS0108), but does not change the IL. As such, you cannot distinguish between a formally newd field vs a field that has been hidden without new.

It would be preferable, though, if you limited yourself to private fields with public accessor properties. And note that in either event: the field in the base type still exists.

like image 74
Marc Gravell Avatar answered Sep 28 '22 00:09

Marc Gravell


I think you'll need to search the base-classes hierarchy for a member with the same name, and if it isn't, then it is new.

I know it's ugly, but as per the comment on this other answer to the same question How do I detect the "new" modifer on a field using reflection?, it says:

I took a look at ILSpy's source code, they are doing the same thing - walking the inheritance chain. They are using Mono.Cecil, but there is no special info that's unavailable via reflection. For more information, take a look at ILSpy's AstBuilder.SetNewModifier method.

Probably not what you have been expecting, sorry for that.

like image 29
Meligy Avatar answered Sep 27 '22 23:09

Meligy