Reputation: 13610
I'm making a class so I can cheat at minesweeper, and is currently building up some generics... but I'm kinda stuck. I want to return a int but how do i convert it?
public T ReadMemory<T>(uint adr)
{
if( address != int.MinValue )
if( typeof(T) == typeof(int) )
return Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T));
else
MessageBox.Show("Unknown read type");
}
Upvotes: 3
Views: 164
Reputation: 11740
I have tried to fix the compiler errors. But I don't know if this is exactly what you are looking for.
You have to cast the result to T
return (T)Convert.ChangeType( MemoryReader.ReadInt( adr ), typeof( T ) );
and you have to return a value when the conditions fail:
return default( T );
This results in:
public T ReadMemory<T>( uint adr )
{
if ( adr != int.MinValue )
{
if ( typeof( T ) == typeof( int ) )
{
return (T)Convert.ChangeType( MemoryReader.ReadInt( adr ), typeof( T ) );
}
else
{
System.Windows.Forms.MessageBox.Show( "Unknown read type" );
}
}
return default( T );
}
Upvotes: 1
Reputation: 1038710
Try casting:
return (T)Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T));
Upvotes: 1
Reputation: 53699
You need to cast the return value from the call to ChangeType
return (T)Convert.ChangeType(MemoryReader.ReadInt(adr), typeof(T));
Upvotes: 7