Question

I have implemented a custom class and tried to set its default value by calling PropertyDescriptor.ResetValue Method. When i make some researches in internet, i saw a link in msdn about this method, its usage and how can be used.

http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.resetvalue.aspx

According to this link, msdn document says:

This method determines the value to reset the property to in the following order of precedence: 1- There is a shadowed property for this property. 2- There is a DefaultValueAttribute for this property. 3- There is a "ResetMyProperty" method that you have implemented, where "MyProperty" is the name of the property you pass to it.

Second methodology does not correspond to my needs. On the other hand, there are not enough usage samples of first and third items.

Could you please explain expecially third one?

Was it helpful?

Solution

I don't know about the first option (I suspect it's to do with declaring one property in a base class and a "new" property in a derived class), but the third seems pretty simple to me:

public class Foo
{
    public string Name { get; set; }

    public Foo()
    {
        ResetName();
    }

    public void ResetName()
    {
        Name = "Some default value";
    }
}

The documentation is saying that if you call ResetValue on the PropertyDescriptor for the Name property, it will call the ResetName method on the component.

I've never actually tried this, but that would be my interpretation.

OTHER TIPS

You can retrieve (2) DefaultValueAttribute like this:

public class MyClass
{
[DefaultValue("my default value")]
public string MyVar { get; set; }

foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(typeof(MyClass)))
    string defaultValue = descriptor.Attributes.OfType<DefaultValueAttribute>().First().Value.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top