1

I'm trying to define a way to set default value on my properties in C#.

I have many elements TextBox and a button to restore default value. I want that when user click on button, the content for TextBox is set to default.

My idea is to set value to null and in setter, check value and if value is null, set default.

There is my code :

private void SetDefault()
{
    Grid actualItem = tabControl.SelectedContent as Grid;
    if (actualItem != null)
    {
        foreach (object elt in actualItem.Children)
        {
            if (elt.GetType() == typeof(TextBox))
            {
                TextBox box = elt as TextBox;
                box.Text = null;
            }
        }
    }
}

example of TextBox:

<TextBox Grid.Row="1" Grid.Column="1"
         Style="{StaticResource TextBoxStyle}"
         Text="{Binding ExamplePropertie,
                Mode=TwoWay,
                UpdateSourceTrigger=PropertyChanged}"/>

For each binded element I wanted to do something like this :

[DefaultValue("default")]
public String ExamplePropertie
{
    get
    {
        return _myProp;
    }
    set
    {
        if (value == null)
            default(ExamplePropertie); // Not working
        else
            _myProp = value;
        OnPropertyChanged(nameof(ExamplePropertie));
    }
}

But default(ExamplePropertie) is not the good way to do that. How can I set value defined with [DefaultValue(value)] ?

4
  • You should introduce a const value alongside your property and use it in both the attribute and the code in the setter. Commented Aug 19, 2016 at 10:53
  • Your code isn't using binding, you are directly assigning values to text boxes. Data binding means that you tell the control where to find the data. What kind of application are you building? Eg in WPF you can specify a default value in the binding expression Commented Aug 19, 2016 at 10:53
  • The code default(ExamplePropertie) just gets the default value of that type which is always null for any reference type. The DefaultValue attribute is unrelated to that. Commented Aug 19, 2016 at 10:59
  • @LasseV.Karlsen so I have to write one const by properties ?@PanagiotisKanavos I added the part with binding, it's on the WPF's view. I will take a look at you solution. Commented Aug 19, 2016 at 11:05

2 Answers 2

2

Well, you can resort to reflection to obtain the value of that attribute but a simpler way would be to simply store the default value as a const:

private const string ExamplePropertieDefault = "default";

[DefaultValue(ExamplePropertieDefault)]
public String ExamplePropertie
{
    get
    {
        return _myProp;
    }
    set
    {
        if (value == null)
            ExamplePropertieDefault;
        else
            _myProp = value;
        OnPropertyChanged(nameof(ExamplePropertie));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

In that case, [DefaultValue()] is useless, isn't it ?
Why would you say that? Do you know what DefaultValueAttribute does? It is used by things like serializers to optimize the output by omitting properties that have their default value. The way a serializer knows that it is safe to omit is that the property has the same value as the one specified in the DefaultValueAttribute. So no, it is not useless. It may be unnecessary in your case but only you can know that.
OK, I didn't know all that. I will keep it then. Thank you for your explanation.
1

[DefaultValue(...)] is an attribute. You cannot get its value by applying default(...) to the name of your property. The process is more complicated: you need to get PropertyInfo object for your property, query it for a custom attribute of type DefaultValueAttribute, and only then grab the value from it.

The process goes much easier with a helper method:

static T GetDefaultValue<T>(object obj, string propertyName) {
    if (obj == null) return default(T);
    var prop = obj.GetType().GetProperty(propertyName);
    if (prop == null) return default(T);
    var attr = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
    if (attr.Length != 1) return default(T);
    return (T)((DefaultValueAttribute)attr[0]).Value;
}

Put this helper method into a separate class, and use it as follows:

_myProp = value ?? Helper.GetDefaultValue<string>(this, nameof(ExampleProperty));

Note: foreach loop in SetDefault can be simplified like this:

foreach (object box in actualItem.Children.OfType<TextBox>()) {
    box.Text = null;
}

1 Comment

obj.GetProperty(propertyName) doesn't not compile, but with obj.GetType().GetProperty(propertyName) it works good ! I didn't know OfType thank you for the tips !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.