[RESOLVED]Problem in Reflection Class

hi All

this is my Class

public class ReflectionTest
public static int Height ;
public static int Width;
public static int Weight ;
public static string Name ;

this is my ActionMethod

public ActionResult Index()

ReflectionTest.Height = 100; // Set value
ReflectionTest.Width = 50; // Set value
ReflectionTest.Weight = 300; // Set value
ReflectionTest.Name = "Perl"; // Set value

Type type = typeof(ReflectionTest); // Get type pointer
FieldInfo[] fields = type.GetFields(); // Obtain all fields
foreach (var field in fields) // Loop through fields
string name = field.Name; // Get string name
object temp = field.GetValue(null); // Get value
if (temp is int) // See if it is an integer.
int value = (int)temp;
ViewBag.Name = ViewBag.Name + "n" + name;
ViewBag.Value = ViewBag.Value + "n" + value;
else if (temp is string) // See if it is a string.
string value = temp as string;
ViewBag.Name = ViewBag.Name + "n" + name;
ViewBag.Value = ViewBag.Value + "n" + value;
return View();

above code give the correct answer.

when i change my class members like below:

(ie) add set and get.

public class ReflectionTest

public static int Height {set;get;}

public static int Width { set; get; }

public static int Weight { set; get; }

public static string Name { set; get; }


it will not working 

any one give me the reason and solution.


Since you are replacing fields with properties in ur ReflectionTest class,

call, GetProperties() instead of GetFields() on Reflection.


it will raise error like this

Error 1 Cannot implicitly convert type ‘System.Reflection.PropertyInfo[]’ to ‘System.Reflection.FieldInfo[]’

after raising below error

Cannot implicitly convert type ‘System.Reflection.PropertyInfo[]’ to ‘System.Reflection.FieldInfo[]’

i will change FieldInfo[] to PropertyInfo[]’

it will work.

now i get another error when i change ReflectionTest properties from static to non static it will raise 

 System.Reflection.TargetException: Non-static method requires a target.

Hi Ananth,

Change this line of code: object temp = field.GetValue(null); // Get value 


var test = new ReflectionTest
Height = 100,
Width = 50,
Weight = 300,
Name = "Perl"

object temp = field.GetValue(test); // Get value

var props = ReflectionTestInstance.GetType().GetProperties().ToList();
var nameValuePairs =new List<Tuple<string,object>>();
     new Tuple<string,object>(p.Name,p.GetValue(ReflectionTextInstance))

Hi Ananth.G,

Thanks for your post.

PawanPal is right,you can refer to his/her reply.You are trying to invoke non-static method without providing object instance reference.

There’s a similar thread:

Non-static method requires a target C#


If there’s anything else I can do for you regarding this matter, please feel free to post back in this forum.

Best Regards,


Leave a Reply