Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through properties of a class

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
US
If I have classes that are either entities or DTOs, so is nothing but properties, is there a way to loop through the properties of the class (not knowing directly what they are) and get or check the values and/or types of the properties.

These would be classes created by a code generated of a table which would create the class with properties for each field in the table.

For example:

Code:
    public class Entity
    {
        public IntType loginID = new IntType();
        public IntType personID = new IntType();
        public StringType userName = new StringType();
        public StringType password = new StringType();

        #region Properties

        public object LoginID
        {
            get
            {
                object value = null;
                return NullHandler.SetDbObjectValueFromValue(loginID, ref value);
            }
            set
            {
                NullHandler.GetValueFromDbObject(value, ref loginID);
            }
        }

        public object PersonID
        {
            get
            {
                object value = null;
                return NullHandler.SetDbObjectValueFromValue(personID, ref value);
            }
            set
            {
                NullHandler.GetValueFromDbObject(value, ref personID);
            }
        }

        public object UserName
        {
            get
            {
                object value = null;
                return NullHandler.SetDbObjectValueFromValue(userName, ref value);
            }
            set
            {
                NullHandler.GetValueFromDbObject(value, ref userName);
            }
        }

        public object Password
        {
            get
            {
                object value = null;
                return NullHandler.SetDbObjectValueFromValue(password, ref value);
            }
            set
            {
                NullHandler.GetValueFromDbObject(value, ref password);
            }
        }
        #endregion
    }

I want to do something like:

Code:
    Entity login = new Entity();

loop through "login" to validate the data I may have gotten from a select of the database.

Thanks,

Tom
 
I figured out how to do it using reflection (not sure if the best way to do it as I heard reflection is a little slow but not sure how else to do it):

Code:
Logins bo = new Logins();
DataSet ds = bo.GetLogins();

Type type = bo.entity.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(bo.entity, null));
}

I am curious as to why I need to pass bo.entity to the GetValue since property is already pointing at the property.

I also need to get at the type of property. If I do a property.PropertyType I get Object back as the property, which it is. But doesn't help me. I need to know what the underlying property type is.

If I do bo.entity.LoginId.GetType() (which is the same property that the loop is pointing at), it knows that it is an Int32 - even though it is defined as an object (as seen above).

The problem is that I don't know the name of the property to do it in code, just the Property from the loop. Is there a way to get the actual property type (unboxed) from the PropertyInfo property.

Thanks,

Tom
 
Reflection is the only way to get the properties of an object. What I am unclear is why you want to do what you are doing? Are you validating data? I am asking because there may be a better way to accomplish what you are trying to do.
 
Actually, I have reflection because that was what I found online.

I want to be able to various things with the class. This class is for the login table. It could just as easily be for the customer table or a stored procedure where the class would have different properties variables and properties. So the properties in the class will be unknown.

I want to be able to validate the whole class for one thing. I also want to be able to loop through each paramater and reset if necessary.

I am not sure how I want to set up the properties. As you can see, I have a set of classes that are datatype classes. One for each datatype (int32, int64, boolean, string etc). These classes are set up so I can handle nulls, know what the inital value I got from a table, know whether a veriable had changed, etc.

The types have various methods and properties:

1) First: original value (never changes
2) Data: current value
3) IsFirstNull: Boolean stating whether field originally was null or not.
4) IsNull: Boolean stating whether value is currently null.
5) SetNull: Sets the current value to null
6) SetFirstNull: Sets the original value to null
7) Reset: Reset _objInitial to _objCurrent and changed flag to false to track when this variable changes again.
This would be necessary if were to write out data to a database record and track when it changes again.
8) Changed: Boolean states whether the variable has changed.
9) DataTypes:
a) public class BoolType : DataType<bool>
b) public class StringType : DataType<string>
c) public class IntType : DataType<int>

I am not sure whether I want to set up properties to access or just access the whole class itself and use the methods directly. There would be a lot of properties for each variable to get at all the properties and methods of the class.

But now it seems that the reflection won't unbox the object as shown above.

If there is a better way, I am open to it.

Thanks,

Tom
 
I guess my question is why new up an object and validate it?
Are you gathering values for the properties from a form? Are they just newed up and then the properties are set?

Here is an example that may help you.

I have a more in depth example that I use in one of my sites, but may over complicate what you need.
 
I am not sure how I am going to use it yet.

The class would be an entity or dto. It would be used to contain many instances of my DataType classes that would come from reading a record out of a database and then possibly validate the data before moving it into the entity class. But I won't know what the different variables are as the class would be created by a source generator that would get the table columns from reading the database for each table.

I want to be able to get the DataType of each field which I can't seem to do using the PropertyType you reference. Since I am setting the properties to object, the Property type gives me back "System.Object" as a result. It doesn't seem to unbox it. But if I use the class directly (entity.loginId.GetType()), it correctly unboxes the variable to int32.

The problem is that using this method I need to know what the variable is where as using the PropertyInfo class and looping through it, I can get the names of the fields but not the type.

Thanks,

Tom
 
Here is some condensed code I use, maybe this will help you:
Code:
   Dim myObj As New YourClass
   Dim MyObjType As Type = myObj.GetType

   Dim properties As PropertyInfo() = MyObjType.GetProperties(BindingFlags.Public Or BindingFlags.DeclaredOnly Or BindingFlags.Instance)

   For Each pi As PropertyInfo In properties
       'Code here to get more property info....
   Next
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top