Question

I'd like to reset the properties of a class back to their default values within a method of the class. My class is instantiated once (is actually a ViewModel in an MVVM framework) and I don't want to destroy and recreate the entire ViewModel, just clear many of the properties. The below code is what I have. The only thing I am missing is how to get the first parameter of the SetValue method - I know it is an instance of the property I am setting, but I cannot seem to figure out how to access that. I get error: "Object does not match target type".

public class myViewModel
{

  ...
  ...

  public void ClearFields()
  {
    Type type = typeof(myViewModel);
    PropertyInfo[] pi = type.GetProperties();
    foreach (var pinfo in pi)
    {
      object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
      if (attributes.Length > 0)
      {
        DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
        pinfo.SetValue(?, def.Value, null);
      }
    }

  }

  ...
  ...


}
Was it helpful?

Solution

You should pass an instance of myViewModel, in your case use this to reference the current instance:

public class myViewModel
{

  ...
  ...

  public void ClearFields()
  {
    Type type = typeof(myViewModel);
    PropertyInfo[] pi = type.GetProperties();
    foreach (var pinfo in pi)
    {
      object[] attributes = pinfo.GetCustomAttributes(typeof(DefaultValueAttribute), false);
      if (attributes.Length > 0)
      {
        DefaultValueAttribute def = attributes[0] as DefaultValueAttribute;
        pinfo.SetValue(this, def.Value, null);
      }
    }

  }

  ...
  ...

}

OTHER TIPS

You should put this as a first parameter. See MSDN for reference:

objType: System.Object

The object whose property value will be set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top