2

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?

eomeroff
  • 9,599
  • 30
  • 97
  • 138
  • I take it someType is determined at runtime? Even if you could find a way, this seems like a bad idea. How do you know what type it is to use it later? – BradleyDotNET May 17 '14 at 17:12
  • If you can say what problem you''re trying to solve it will be better to answer. – Sriram Sakthivel May 17 '14 at 17:19
  • Had the same problem when using reflection to set properties from a DB. I know the name of the property but I don't know its type. I know the name of the DB column but I don't know its type. So, good question. (And good answer.) – TobiMcNamobi Apr 15 '15 at 09:39

2 Answers2

5

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.

MSDN: System.Convert.ChangeType

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
-1

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

Community
  • 1
  • 1
Kumar Manish
  • 3,746
  • 3
  • 37
  • 42
  • A good explanation of the as operator, but I don't think this answers the question of doing a cast to a run-time determined type (which this won't allow of course) – BradleyDotNET May 17 '14 at 17:17
  • @BradleyDotNET With the help of As, u can cast the object at runtime, but if you want to use runtime type , you can go with "Dynamic". dynamic is a new static type that acts like a placeholder for a type not known until runtime. – Kumar Manish May 17 '14 at 17:36