Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list fields of current class in C# Reflection (problem with this.GetType())?

This is accepted by the compiler:

FieldInfo[] fieldInfos;
fieldInfos = typeof(MyClass).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

This is NOT accepted by the compiler:

FieldInfo[] fieldInfos;
fieldInfos = typeof(this.GetType()).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

How to fix second syntax?

like image 955
user310291 Avatar asked Dec 07 '22 23:12

user310291


2 Answers

You don't need typeof() around a GetType call since it already returns a Type object. typeof is a special syntax for getting a Type object from a type name, without having to do something like Type.GetType("Foo").

FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic |
                                 BindingFlags.Instance);
like image 89
Matti Virkkunen Avatar answered Dec 09 '22 13:12

Matti Virkkunen


typeof does not permit you to pass in an instance of System.Type. typeof is an operator whose sole parameter is a type (like Int32, or object, or MyClass) and it returns an instance of System.Type. When you already have an instance of an object, just call GetType so get an instance of System.Type. Therefore, just say

fieldInfos = this.GetType()
                 .GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
like image 26
jason Avatar answered Dec 09 '22 11:12

jason