I have a generic function static Log<T>(T Log). I would like to check type of T and decide what to do next.
This is what I got so far:
public static void Log<T>(T log)
{
switch (typeof(log))
{ ... }
}
What am I doing wrong? My error is that typeof(log) doesnt work.
expression= An integral or string type expression (From MSDN)http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx
The
typeofkeyword returns neither of these. You can’t uselog.GetType()as you need to meet the criteria above of whichTypeisn’t suitable.To be on the safe side I would limit this to
ifstatements with the corresponding types as this will achieve the same thing.EDIT:
If you have for arguments sake you have:
And you want a generic method to move the Vehicle you could do something called
generic type constraintshttp://msdn.microsoft.com/en-us/library/bb384067.aspx
T has to be a Vehicle now, so you have access to the methods in Vehicle. You can pass a car to the method and it will still be able to call the
MoveVehiclemethod.