views:

300

answers:

1

Hi everyone,

I really can't figure this one out! (if it's even possible). From a WCF service we are receiving product information. A product datacontract has some members that are defined as strings (but are actually integers), but we want to process them as integers.

When I change the datatype in the contract on the client side from string to int, my problem is solved. However, some products have a string.Empty value, which can't be deserialized into an int. Is there anyway around this? Really don't want to convert my resultset after deserialization...

+1  A: 

Well, since those DataContract classes you get are always partial classes, you could just simply add a second partial class, and provide "PropertyAsInt" properties.

Something like this:

public partial class Product
{
   public int ProductNumberAsInt
   {
       get 
       { 
          if(!string.IsNullOrEmpty(ProductNumber))
          {    
             int result = -1;

             if(int.TryParse(ProductNumber, out result)
                return result;
             else
                return -1;
          }

          return 0;
       }
    }
 }

So you would just simply define a ProductNumberAsInt property, which would inspect the underlying string property called ProductNumber. If it's null or string.Empty, just return a default value, e.g. -1 or 0 or whatever works for you.

If it's not null/empty, you can try to convert it to an Int, and if successful, return that int - otherwise return another indicator (again, take your pick, -1, 0, whatever makes sense for you).

That way, you don't have to mess with the WCF data contracts, no messy manual hacking, and you can tweak those extra properties as you need them.

Marc

marc_s
He marc, thanx for the swift reply. This is indeed an option I considered. Problem is that there is three of these properties, and I would have to rewrite my code to work on the new properties instead of the old ones. As for returnvalues, making them nullable would solve that problem..
Syg