2

Some code:

foreach (System.Reflection.PropertyInfo pi in myObject.GetType().GetProperties())
{
    if (pi.CanWrite)
    {
        object value = pi.GetValue(Properties, null);

        // if (value is not default)
        // {
        X.addAttribute(pi.Name, value);
        // }
    }
}

What I'm trying to do is not-call the line 'X.addAttribute...' if the property is at its DefaultValue. I assume there's some way of getting the DefaultValue of a property so I can do a comparison?

For my purpose I am trying to get the 'default' value as defined by DefaultValueAttribute.

Any help is appreciated, cheers.

nawfal
  • 70,104
  • 56
  • 326
  • 368
Wex
  • 4,434
  • 3
  • 33
  • 47
  • Answers will depend based on how you define "default value". The two obvious definitions are CLR-Default (`null` for reference types, 0 for value types) or the `DefaultValueAttribute`. Can you edit your question to clarify which you are interested in? – Paul Turner Feb 16 '10 at 12:01
  • Hi, apologies; I should have specified. It was default as defined via DefaultValueAttribute. – Wex Feb 16 '10 at 12:05

3 Answers3

5

Below is the method I use to get a default value of any runtime-type it will return 'null' for non value types otherwise it will return the default value type (it includes caching of value types for extra perf):

private static readonly Dictionary<Type, object> DefaultValueTypes 
    = new Dictionary<Type, object>();

public static object GetDefaultValue(Type type)
{
    if (!type.IsValueType) return null;

    object defaultValue;
    lock (DefaultValueTypes)
    {
        if (!DefaultValueTypes.TryGetValue(type, out defaultValue))
        {
            defaultValue = Activator.CreateInstance(type);
            DefaultValueTypes[type] = defaultValue;
        }
    } 

    return defaultValue;
}
mythz
  • 141,670
  • 29
  • 246
  • 390
3

Assuming you're trying to get the DefaultValue attribute, use GetCustomAttributes on your PropertyInfo objects.

Sylvestre Equy
  • 385
  • 1
  • 8
-3

First, You must always initialize the field with value you want as a default.

Something similar

    class UnitManager
    {
      private int value;

      [DefaultValue("0")]
      public int Value
      {
       get { return this.value; }
       set { this.value = value; } 
      }
    } 

Then simply use

    UnitManager manager = new UnitManager()

    int startValue = manager.Value;
Asad
  • 21,468
  • 17
  • 69
  • 94