How to switch between “possible” type of an object? [duplicate]

A couple of options:

  • If you’re using C# 4, you could use dynamic typing, and split the method into a number of overloads:

    public Uri GetUri(dynamic obj)
    {
        return GetUriImpl(obj);
    }
    
    private Uri GetUriImpl(Entry entry)
    {
        ...
    }
    
    private Uri GetUriImpl(EntryComment comment)
    {
        ...
    }
    

    In this case you’d probably want some sort of “backstop” method in case it’s not a known type.

  • You could create a Dictionary<Type, Func<object, Uri>>:

    private static Dictionary<Type, Func<object, Uri>> UriProviders = 
        new Dictionary<Type, Func<object, Uri>> {   
        { typeof(Entry), value => ... },
        { typeof(EntryComment), value => ... },
        { typeof(Blog), value => ... },
    };
    

    and then:

    public Uri GetUri(object obj)
    {
        Func<object, Uri> provider;
        if (!UriProviders.TryGetValue(obj.GetType(), out provider))
        {
            // Handle unknown type case
        }
        return provider(obj);
    }
    

    Note that this won’t cover the case where you receive a subtype of Entry etc.

Neither of these are particularly nice, mind you… I suspect a higher level redesign may be preferable.

Leave a Comment