views:

293

answers:

4

How can I make this function reliably cast sourceValue to type T where sourceValue is bool and T is int?

public static T ConvertTo<T>(Object sourceValue)
{
  // IF IS OF THE SAME TYPE --> RETURN IMMEDIATELY
  if (sourceValue is T)
    return (T) sourceValue;

  var val = ConvertTo(sourceValue, typeof (T));
  return (T) val; 
}

Currently, this throws an InvalidCastException when trying to convert false to 0 and true to 1. The types are not predefined, which is why generics must be used here. However, the only case where it fails is when T:Int32 and sourceValue:Boolean.

+4  A: 

Is false=0 and true=1? Maybe in other languages, but here the cast makes no sense. If you really need this, I think it's a special case.

spender
+1 this does not seem to warrent generics, if the types are predefined.
astander
`Convert.ToInt32` does exactly that - converts false to 0 and true to 1. I guess it does make sense.
Kobi
The types are not predefined, which is why generics must be used here. However, the only case where it fails is when T:Int32 and sourceValue:Boolean.
Mark Richman
+2  A: 

I would think converting a bool to an int is undefined. However, I don't believe its appropriate to write out that special case explicitly in your function either, otherwise your function is incongruent with the way .NET implicitly treats ints and bools.

You're best off writing:

int value = someFlag ? 1 : 0;
Juliet
A: 

I needed a highly generic solution. This is the best I could come up with:

public static T ConvertTo(Object sourceValue)
    {
      // IF IS OF THE SAME TYPE --> RETURN IMMEDIATELY
      if (sourceValue is T)
        return (T) sourceValue;

      var val = ConvertTo(sourceValue, typeof (T));

      // SPECIAL CASE: Convert bool(sourceValue) to int(T)
      if (val is bool)
      {
        var b = (bool) val;
        if (b)
          return (T) (object) 1; // if val is true, return 1

        return (T) (object) 0;
      }

      return (T) val;
    }
Mark Richman
@Mark: This doesn't compile, the same as the original example in your question. Both examples call another overload of the `ConvertTo` method that you're not showing us. If you give us code that we can actually compile and test then I'm sure that somebody will be able to help out.
LukeH
+1  A: 

Not entirely sure what you're trying to do, but .net does support conversion of bool to int:

Convert.ToInt32(true);

It can also take an object, and figure out if it's a bool.
See also: Convert.ToInt32(bool), Convert.ToInt32(Object)

Kobi