Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting generic objects back to the original object in C#

Tags:

c#

casting

I having trouble casting from a generic back to the original object in C#

private static bool OpenForm<T>( )
{
    List<T> list = FormManager.GetListOfOpenForms<T>();
    if ( list.Count == 0 )
    {
        // not opened
        return false;
    }
    else
    {
        // opened
        foreach ( T f in list )
        {
            T ff = ( T ) Convert.ChangeType( f, typeof( T ) );

if I type ff. and intellisense pops up with the just a few methods and properties.

how can I have a variable here where it exposes all properties and methods of ff

        }
        return true;
    }
}
like image 949
trailerman Avatar asked Jan 28 '26 09:01

trailerman


2 Answers

Since it is a generic method, T could literally be any type, down to a simple object. The compiler - and likewise the intellisense engine - has no idea what T is until runtime. Note that this is of course the behavior you want, and it is the reason you use generics in the first place. In this case, using static typing, there is no way to access the members of T outside of reflection.

Now what I believe you are looking for is a constraint, that is to say that all Ts will always be of a certain base type. For example, if all Ts will be Forms, you can put a constraint on the method and then access the members of Form:

private static bool OpenForm<T>() where T : Form
{
    List<T> list = FormManager.GetListOfOpenForms<T>();
    if ( list.Count == 0 )
    {
        // not opened
        return false;
    }
    else
    {
        // opened
        foreach ( T f in list )
        {
            f.Text = "You found me!";
        }
    }
}

Note I have omitted your conversion from T f to T ff since it would do nothing.

like image 79
lc. Avatar answered Jan 29 '26 22:01

lc.


if T has some sort of common base class(common type), use generic constraints so that the compiler will know that at minimum T will support the methods on the common class. http://msdn.microsoft.com/en-us/library/d5x73970.aspx

like image 27
Hardrada Avatar answered Jan 29 '26 23:01

Hardrada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!