0

When trying to look at all instance attrs of a given class that has been instantiated, I could do this in python:

myObject.__dict__ to see all key/value pairs stored for this instance.

Can this be done in C#?

JacobIRR
  • 8,545
  • 8
  • 39
  • 68

2 Answers2

3

Not quite a duplicate, so I'm not flagging it as such, but take a look at How to get the list of properties of a class?. There are some good examples of how to use the Reflection library. For example, you can use myObject.GetType().GetProperties(). This only returns the properties that have at least one accessor (get or set). So, an instance with public int num = 0 will not be included in the return, but public int num {get; set;} = 0 will be.

Type.GetFields(), and Type.GetField(string) in the Reflection library may also be close to what you're looking for. For example:

Type t = typeof(myType);
FieldInfo[] arr = t.GetFields(BindingFlags.Public|BindingFligs.NonPublic);
var newInstance = new myType();
foreach (FieldInfo i in arr) 
{ 
    Console.WriteLine(i.GetValue(newInstance));
}
zambonee
  • 1,599
  • 11
  • 17
  • In Python terms, I'm looking for all instance attributes. In C# terms, this would mean all properties and fields. Is there a way to show the fields too? – JacobIRR Oct 06 '17 at 18:20
  • When I try this, for an instance that I know has many attributes and fields, I get: `System.Reflection.PropertyInfo[];` – JacobIRR Oct 06 '17 at 18:29
  • There are also `Type.GetFields(BindingFlag)` and `Type.GetField(string)` in the Reflection library, which might be closer to `myObect.__dict__`. – zambonee Oct 06 '17 at 18:35
  • but a type is not an instance of a class. If I have class `Person` and I instantiate `Bob`, the person. How could I see e.g. Bob's height, weight, birthday, etc.? – JacobIRR Oct 06 '17 at 18:37
0

I'm not sure of any methods that do that specifically. However, you can JSON encode the object and print that as a somewhat similar concept.

var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourDictionary);
//output json

It might also be worthwhile to make it do a "pretty print" so it's easier to read:

How do I get formatted JSON in .NET using C#?

This uses JSON.net, but I like that better anyway:

string json = JsonConvert.SerializeObject(yourDictionary, Formatting.Indented);
Console.WriteLine(json);
Kevin Nelson
  • 7,613
  • 4
  • 31
  • 42