Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Reflection GetProperties method not returning values

Can some one explain to me why the GetProperties method would not return public values if the class is setup as follows.

public class DocumentA {     public string AgencyNumber = string.Empty;     public bool Description;     public bool Establishment; } 

I am trying to setup a simple unit test method to play around with

The method is as follows and it has all the appropriate using statements and references.

All I'm doing is calling the following but it returns 0

PropertyInfo[] pi = target.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

But if I setup the class with private members and public properties it works fine.

The reason I didn't setup up the the class the old school way was because it has 61 properties and doing that would increase my lines of code to at least triple that. I would be a maintenance nightmare.

like image 900
gsirianni Avatar asked Oct 20 '11 15:10

gsirianni


People also ask

What is GetProperties C#?

GetProperties() Returns all the public properties of the current Type.

What is GetType Getproperty in c#?

GetProperties() Method is used to get the properties of the current Type.

What is reflection in programming C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


2 Answers

You haven't declared any properties - you've declared fields. Here's similar code with properties:

public class DocumentA {     public string AgencyNumber { get; set; }     public bool Description { get; set; }     public bool Establishment { get; set; }      public DocumentA()      {         AgencyNumber = "";     } } 

I would strongly advise you to use properties as above (or possibly with more restricted setters) instead of just changing to use Type.GetFields. Public fields violate encapsulation. (Public mutable properties aren't great on the encapsulation front, but at least they give an API, the implementation of which can be changed later.)

like image 151
Jon Skeet Avatar answered Sep 22 '22 10:09

Jon Skeet


Because the way you have declared your class now is using Fields. If you want to access the fields trough reflection you should use Type.GetFields() (see Types.GetFields Method1)

I don't now which version of C# you're using but the property syntax has changed in C# 2 to the following:

public class Foo {   public string MyField;   public string MyProperty {get;set;} } 

Wouldn't this help in reducing the amount of code?

like image 41
Wouter de Kort Avatar answered Sep 25 '22 10:09

Wouter de Kort