I have some type that Type someType
that I want to cast in runtime
for example I want to do :
var customers = GetCustomers() as someType[]
How to do this?
I have some type that Type someType
that I want to cast in runtime
for example I want to do :
var customers = GetCustomers() as someType[]
How to do this?
You cannot use as
to cast a type known at runtime: the expression would be invalid at compile-time since you'd have to use typeof(T)
which cannot be used together with as
.
What you can use though is System.Convert.ChangeType(object, Type)
. Here the second parameter can use typeof(T)
and combined with a control statement you can convert the input at runtime to the correct type.
You should ask yourself whether this is something you want though: types known only at runtime will leave you with little use.
The as operator attempts to cast an object to a specific type, and returns null if it fails.
Example:
StringBuilder b = someObject as StringBuilder; if (b != null) ...
Also related:
The cast operator attempts to cast an object to a specific type, and throws an exeption if it fails.
Example:
StringBuilder b = (StringBuilder)someObject.
Refer this link :Difference between is and as keyword