Mark Richman
Mark Richman

Reputation: 29730

Cast bool to T where T is int

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.

Upvotes: 0

Views: 2839

Answers (5)

Kris Adams
Kris Adams

Reputation: 710

As a follow-up to Mark's own answer. I think this is a decent solution:

        protected Nullable<T> ConvertTo<T>(Object sourceValue) where T : struct, IComparable
    {
        if (sourceValue is T)
            return (T)sourceValue;

        if (sourceValue == null)
        {
            return null;
        }
        try
        {
            var val = Convert.ChangeType(sourceValue, typeof(T));
            return (T)val;
        }
        catch (FormatException)
        {
            return null;
        }

    }

Upvotes: 0

Kobi
Kobi

Reputation: 138147

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)

Upvotes: 1

Mark Richman
Mark Richman

Reputation: 29730

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;
    }

Upvotes: -1

Juliet
Juliet

Reputation: 81536

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;

Upvotes: 2

spender
spender

Reputation: 120548

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.

Upvotes: 4

Related Questions