David
David

Reputation: 1196

Casting works but can't convert whats the difference and why

Have the following code which works fine.

MyType convertedItem = (MyType)item;

However I get a compiler error from

var convertedItem = item as MyType;

Cannot convert type 'OtherType' to 'MyType' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

Can anyone explain why \ when this occurs. An explicit cast works fine but AS wont even compile.

** How do I get 'AS' functionality in this situation. Namely I need to do a trycast and would prefer not to invoke the exceptionhandler to accomplish it. **

Upvotes: 0

Views: 231

Answers (2)

felix-b
felix-b

Reputation: 8498

For example, the following types would give CS0039:

class MyType
{
}

class MyOtherType
{
}

MyOtherType item = new MyOtherType();
var convertedItem = item as MyType;

In the above example, the compiler has determined that given the types participating in the cast, it's impossible to perform the requested conversion.

Here providing conversion operators would solve the problem.

EDIT: working around this error with casting to Object is not recommended, as it defeats the purpose of the type system

Upvotes: -1

Jlalonde
Jlalonde

Reputation: 483

as doesn't work with anything that is a struct. Logically we can understand this because a struct is non nullable by default. The suggestions of casting to object work by cheating and boxing the struct

Upvotes: 2

Related Questions