Search This Blog

Saturday 20 July 2019

Trim all string properties from class

Step 1: - Class

public class Class1
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

Step 2: - Generic Method

public T TrimStringProperties<T>(object obj)
{
    var stringProperties = obj.GetType().GetProperties().Where(p => p.PropertyType == typeof(string));

    foreach (PropertyInfo propertyInfo in stringProperties)
    {
        string value = (string)propertyInfo.GetValue(obj, null);
        if (value != null)
            propertyInfo.SetValue(obj, value.Trim(), null);
    }
    return (T)obj;
}

Step 3: - Main Method

static void Main(string[] args)
{
// With Space value store in the property
    Class1 class1 = new Class1();
    class1.Prop1 = " Property1";
class1.Prop2 = "Property2 ";

// Class Object
Program p = new Program();

// This line trim the extra spaces from the value
class1 = p.TrimStringProperties<Class1>(class1);
}


OR

Use can use trim property value in the class itself.


public class Class1
{
    private string _Prop1 = string.Empty;

    private string _Prop2 = string.Empty;

    public string Prop1
    {
        get { return _Prop1; }
        set { _Prop1 = value.Trim(); }
    }

    public string Prop2
    {
        get { return _Prop2; }
        set { _Prop2 = value.Trim(); }
    }
}