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#?
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));
}
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);