Casting a non-generic type to a generic one
        Posted  
        
            by John Sheehan
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by John Sheehan
        
        
        
        Published on 2010-03-29T04:47:57Z
        Indexed on 
            2010/03/29
            4:53 UTC
        
        
        Read the original article
        Hit count: 446
        
I've got this class:
class Foo { 
    public string Name { get; set; }
}
And this class
class Foo<T> : Foo {
    public T Data { get; set; }
}
Here's what I want to do:
public Foo<T> GetSome() {
    Foo foo = GetFoo();
    Foo<T> foot = (Foo<T>)foo;
    foot.Data = GetData<T>();
    return foot;
}
What's the easiest way to convert Foo to Foo<T>? I can't cast directly InvalidCastException) and I don't want to copy each property manually (in my actual use case, there's more than one property) if I don't have to. Is a user-defined type conversion the way to go?
© Stack Overflow or respective owner