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;
}
}
Since it is a generic method,
Tcould literally be any type, down to a simpleobject. The compiler – and likewise the intellisense engine – has no idea whatTis 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 ofToutside 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 allTs will beForms, you can put a constraint on the method and then access the members ofForm:Note I have omitted your conversion from
T ftoT ffsince it would do nothing.