2

I have a generic base class for a WPF UserControl. One of the dependency properties is defined as

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register
    ( "Value"
    , typeof(T)
    , typeof(ValidatingTextBox<T,C>)
    , new FrameworkPropertyMetadata(default(T), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)
    );

where I write default(T) for the default value I realize that what I really want is something different. For reference types the default(T) is null which is not what I want in this special case. I would like to build a custom default operator if possible that allows me to return my own idea of what default should be. Is this possible?

For example I imagine

public static T MyDefault<T>(){

    switch(typeof(T)){
        case (typeof(String)) : return "";
        case (typeof(Foo)) : return new Foo();  
    }

    }

obviously the above will not compile for many reasons but the intent should be clear. Is there a way to do this?

In C++ I would use traits classes to get this but I don't think that is possible in C#. In C++ I would end up doing something like.

DefaultGenerator<T>.Default
bradgonesurfing
  • 30,949
  • 17
  • 114
  • 217
  • possible duplicate of [Is there a better alternative than this to 'switch on type'?](http://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type) – Avner Shahar-Kashtan Apr 08 '14 at 07:26
  • 1
    @AvnerShahar-Kashtan It's not a duplicate, OP specifically asks to return custom default types. The suggested means are similar, but not the same. – aevitas Apr 08 '14 at 07:27

1 Answers1

3

Something like this?

private static Dictionary<Type,Func<object>> factory = new Dictionary<Type,Func<object>>{
        {typeof(string), ()=> String.Empty },
        {typeof(MyClass), ()=> new MyClass() },
    };
public static T MyDefault<T>()
{

    Type t = typeof(T);
    Func<object> func = null;

    if(factory.TryGetValue(t, out func))
        return (T)func();
    else
        return default(T);
}
Lorentz Vedeler
  • 5,101
  • 2
  • 29
  • 40
  • I would recommend storing the factory dictionary in a static dictionary, populated on first use (when it's `null`), and then using `TryGetValue` on the dictionary to avoid two lookups, otherwise this is the right approach. – Lasse V. Karlsen Apr 08 '14 at 07:43