Ive seen this code :
StringBuilder Foo<T> (T arg)
{
if (arg is StringBuilder)
return (StringBuilder) arg; // Will not compile
...
}
however :
StringBuilder Foo<T> (T arg)
{
StringBuilder sb = arg as StringBuilder;
if (sb != null) return sb;
...
}
will compile.
why is that ? what the compiler is afraid of ?
p.s. ive seen another solution which :
(StringBuilder) (object) arg
I think, cause there is no guranteed conversion between type
TandStringBuilder.Specifying it like
arg as StringBuilder, if coversion fails, it will return anulland not exception, like in previouse case.Nullis a valid case, in this function, like a returning type.