I have an object called Job and inside of it I have strings, ints, and an enum as public objects. Each job is then placed into a Queue and I iterate through the queue in the process.
What I want to do is that when I Dequeue() each job, I can generically iterate through each job and write the public object names and values to the console.
I figured out how to write the object names to console and I can obviously write the values, but the problem is that I don't know how to get each public string/int/enum from the Job object.
I've looked at C# object dumper C#: How to get all public (both get and set) string properties of a type How to select all the values of an object's property on a list of typed objects in .Net with C# but don't understand how I would use either of the accepted answers there.
Here's the code to my Job class:
class Job
{
#region Constructor
public Job()
{
}
#endregion
#region Accessors
public int var_job { get; set; }
public jobType var_jobtype { get; set; } //this is an enum
public string var_jobname { get; set; }
public string var_content { get; set; }
public string var_contenticon { get; set; }
#endregion
}
Here's the code that's returning the variable's name: (from https://stackoverflow.com/a/2664690/559988)
GetName(new {Job.var_content}) //how I call it
static string GetName<T>(T item) where T : class
{
return typeof(T).GetProperties()[0].Name;
}
Ideally I'd have an output to console like this:
Queuing Jobs Now
--------------------
var_job = its value
var_jobtype = its value
var_jobname = its value
var_content = its value
var_contenticon = its value
Thoughts?
What I think you're looking for is
PropertyInfo.GetValue
. Perhaps something like this will help (from memory so hopefully it'll work as is):You can also something similar with your object's fields if you tend to use those instead of properties.
These will dump to the console, but it should be straight forward enough to change them to write to any stream.
Update
If you start getting
NullReferenceException
's from a property not being set, rather than wrapping it in atry...catch
, you should do some proactive checks against the value returned fromPropertyInfo.GetValue
: