1

Meaning, is there anything I can do, so that when I try and assign a short to a bool, it invokes my custom type conversion from short to bool?

I have a DB first POCO model, and every true/false value in the entire data model generated off the DB of 250 tables is either short? or short. The original RDBMS didn't have the concept of a boolean value.

Now I can't just change all the shorts to bools because I get type conversion errors when querying the DbContext. I could substitute bool for a custom value type if I could get and set it's value without needing a Value property, e.g.

public struct BoolThatLikesShorts
{
...
}

and then use it like BoolThatLikesShorts IsActive = (short)1; and later on use it like

if (IsActive)
{
...
}

so that I we effectively have a complete bool equivalent.

ProfK
  • 49,207
  • 121
  • 399
  • 775
  • I am not aware of any solution making this possible.. You can always write an extension method for short called ToBool(), but you probably know this.. – Kenny Thompson Nov 27 '13 at 14:07

2 Answers2

1

not implicitly but you could create an extension method

public static bool CustomBoolConversion( this short value )
{
    bool retVal;

    // custom implementation

    return retVal;
}

Usage:

short s = 1;
bool b = s.CustomBoolConversion();
Moho
  • 15,457
  • 1
  • 30
  • 31
1

If you mean, wherever you place this code:

short foo = 4;
bool bar = (bool)foo; // Or even without cast.

You have your custom TypeConverter (or whatever) called, then no, there is no such a easy way of doing this.

However, there are some workarounds:

  • Create a custom valuetype where it can be implicitly casted to bool and explicitly from short where YourType is a struct which has two cast operators defined within. So you could have

    bool bar = (YourType)(short)3;
    
  • Create an extension, which will allow you to cast like this

    bool bar = ((short)3).ToBool();
    

Regarding to your updated answer, try peeking at this: Convert value when mapping.

Community
  • 1
  • 1
AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • I can place an attribute on `foo`, but I can't change the assignment into a cast. This is for the automagic materialization of EF entity classes from DB query results. – ProfK Nov 27 '13 at 16:53
  • @ProfK why don't you expand the question then explaning this and many other a thing about the technologies you are using, like EF, data mapping and so on? – AgentFire Nov 27 '13 at 17:15
  • I have expanded the question. I came up with a playfull experiment that might even work. A struct called `YesNo` with implicit cast operators to and from `bool` and `short`. I just don't like the name `YesNo`. Maybe `BOOL`? – ProfK Nov 27 '13 at 18:34