Question

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
Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top