I want to build a method that accepts parameter as Type
like
void M1(Type t)
{
// check which type it is
}
and call it like
M1(typeof(int));
I have no idea how to check type
in method body.
I have tried
if (t is double)
But it is giving warning
The given expression never provided type (double)
Please help me for checking the type of parameter.
If you want to check for an exact type, you can use:
if (t == typeof(double))
That's fine for double
, given that it's a struct, so can't be inherited from.
If you want to perform a more is-like check - e.g. to check whether a type is compatible with System.IO.Stream
- you can use Type.IsAssignableFrom
:
if (typeof(Stream).IsAssignableFrom(t))
That will match if t
is System.IO.MemoryStream
, for example (or if it's System.IO.Stream
itself).
I always find myself having to think slightly carefully to work out which way round the call goes, but the target of the call is usually a typeof
expression.
See more on this question at Stackoverflow