Kal_Torak
Kal_Torak

Reputation: 2551

Can't do (expression yielding System.Type)object cast?

I've got an object[] array which contains some mixture of builtin types, like Int/Byte/String, and I'm trying to cast at runtime from object to the correct type, then handing that casted data to a 3rd party library that has Write(builtin type overloads) method.

I thought I could just do Obj.Write((expression yielding System.Type)objArg), but it errors on me.

Here's a code sample that explains it better:

    object testData = (int)42;
    int final = (GetAType())testData;

    private Type GetAType()
    {
        return typeof(Int32);
    }

Any suggestions? Alternate ways to accomplish this would be helpful also.

For some context, here's my original problem. 3rd party library with a bunch of overloads for different types.

3rdPartyLibrary.Write(bool source)
3rdPartyLibrary.Write(int16 source)
3rdPartyLibrary.Write(int32 source)
3rdPartyLibrary.Write(string source)

I'm trying to abstract a layer between 3rdPartyLibrary and the rest of my code

Such that I can have
Object[int32]
Object[int16]
Object[string]
Object[int32]

I'm trying to do something simple seeming, like this (psuedo-coded)

loop Object[]
{
  3rdPartyLibrary.Write( (object[i].GetType()) object[i] )
}

I've been reading all the similar sounding question, it looks like this may not be possible?

Upvotes: 0

Views: 120

Answers (2)

Guffa
Guffa

Reputation: 700670

What you are looking for would be pointless, as the result still would have to have a single type for all operations, and that would have to be object to handle all the different types.

Just use a switch for the types that you support:

foreach (object item in Object) {
  switch (item.GetType().Name) {
    case "System.Int16":
      3rdPartyLibrary.Write((Int16)item);
      break;
    case "System.Int32":
      3rdPartyLibrary.Write((Int32)item);
      break;
    case "System.Boolean":
      3rdPartyLibrary.Write((bool)item);
      break;
    case "System.String":
      3rdPartyLibrary.Write((string)item);
      break;
    default:
      throw new ArgumentException("Unhandled type '" + item.GetType().Name + "'.");
}

Upvotes: 1

Diego Mijelshon
Diego Mijelshon

Reputation: 52745

Casts are compile-time constructs; you can't use the result of a call in a cast operator.

There are two ways to solve your problem.

If you're using .NET 4:

3rdPartyLibrary.Write((dynamic)object[i]);

Otherwise, you'll have to use reflection to select the right overload based on the parameter type and then invoke it.

Upvotes: 1

Related Questions