Question

I have a huge user-defined class with lots of properties and some of them has to be set with a certain value.

To be more specific, all the public properties with the type of string in this user-defined class have to be "emptied" at the end of execution.

So i reached all the public properties one by one (like 300 properties) and assigned them with my 300 lines of code. What i did to solve this problem, did what i needed, but didn't satisfy me of course.

So i decided to write a Helper Method (as Extension Method) in C# that iterates through the properties of an object instance and access / manipulate them dynamically. I've seen some similar questions about iterating through properties in here, but didn't see anything about changing property values so far. Here is what i tried:

public static void SetDefaultStringValues(this Object myObject)
{
    PropertyInfo[] aryProperties = entityObject.GetType().GetProperties();

    foreach (object property in aryProperties)
    {
        if (property is String) 
        {
            //property = String.Empty;
        }
    }
}

The commented part had to be the line that i set the variables but that wasn't really a success story :) I'll appreciate any help.

Was it helpful?

Solution 2

You can use PropertyDescriptor of System.ComponentModel for lazy coding. Assuming you want to iterate over public instance methods (not statics) you can try the following sample:

Test class:

public class TestClass
{
    private int mIntMemeber = 0;                    // # to test int type   
    private string mStringMember = "abc";           // # to test string type (initialized)
    private string mNullStringMember = null;        // # to test string type (null)

    private static string mStaticNullStringMember;  // # to test string type (static)

    // # Defining properties for each member
    public int IntMember                            
    {
        get { return mIntMemeber; }
        set { mIntMemeber = value; }                
    }

    public string StringMember                      
    {
        get { return mStringMember; }
        set { mStringMember = value; }
    }

    public string NullStringMember
    {
        get { return mNullStringMember; }
        set { mNullStringMember = value; }
    }

    public static string StaticNullStringMember
    {
        get { return mStaticNullStringMember; }
        set { mStaticNullStringMember = value; }
    }
}

SetDefaultStringValues() Extension Method:

public static string SetDefaultStringValues(this TestClass testClass)   
{
    StringBuilder returnLogBuilder = new StringBuilder();
    // # Get all properties of testClass instance
    PropertyDescriptorCollection propDescCollection = TypeDescriptor.GetProperties(testClass);
    // # Iterate over the property collection
    foreach (PropertyDescriptor property in propDescCollection)
    {
        string name = property.Name;
        Type t = property.PropertyType; // # Get property type
        object value = property.GetValue(testClass); // # Get value of the property (value that member variable holds)

        if (t == typeof(string)) // # If type of propery is string and value is null
        {
            property.SetValue(testClass, String.Empty); // # Set value of the property (set member variable)
            value = String.Empty; // # <-- To prevent NullReferenceException when printing out
        }

        returnLogBuilder.AppendLine("*****\nName:\t{0}\nType:\t{1}\nValue:\t{2}", name, t.ToString(), value.ToString());
    }

    returnLogBuilder.AppendLine("*****");
    return returnLogBuilder.toString();
}

You could also check if value is null within the loop. SetDefaultStringValues method parameter could be any object instance. You can change it to SetDefaultStringValues(this object o) and use it as extension method for your defined class instance.

OTHER TIPS

Use PropertyInfo.SetValue method, more on this in here

You need a different syntax in order to check the property type; furthermore, you shold check that the property has a public setter.

if (property.PropertyType == typeof(string) && property.GetSetMethod() != null)
    property.SetValue(entityObject, "");
    foreach (PropertyInfo property in aryProperties)
    {
        if (property.PropertyType == typeof(string) && property.CanWrite) 
        {
            property.SetValue(myObject, "", null);
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top