How to get a list of variables in a class in C#
You can use reflection.
Example:
class Foo {
public int A {get;set;}
public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
From here: How to get the list of properties of a class?
Properties have attributes (properties) CanRead
and CanWrite
, which you may be interested in.
Documentation: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx
Your question is a little vague, though. This may not be the best solution... depends heavily on what you're doing.
Simeon
Updated on June 13, 2022Comments
-
Simeon almost 2 years
How do I get a list of all the variables in a class, to be used in another class to indicate which Variables will and can be changed by it for example. This is mainly for not having to rewrite a enum when some variables are changed or added.
Edit: I want to create a class that has some stats that can be modified (Main), and another type of class (ModifyingObject) that has a list of all the stats that it can change and by how much. I want to easily get the variables of the main class, and add a list of which variables does the modifying class change. if I have let's say 10 variables for different stats how can I easily list all the stats the ModifyingObject class can change in the Main class.
public class Main{ float SomeStat = 0; string SomeName = "name"; List<ModifyingObject> objects; bool CanModifyStatInThisClas(ModifyingObject object){ //check if the custom object can modify stats in this class } } public class ModifyingObject{ .... }
-
Simeon about 11 yearsdoing an Upgrade system in unity. And i have lots of items that change a classes stats. Some may not even change one stat and others may change them all.
-
tnw about 11 years@Simeon I'm confused by your comment. Was this answer helpful or were you looking for something else?
-
Simeon about 11 yearsyes it was with this i can write universal upgrades that work with any class for example that has the name property and it will change that.