Type conversion

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • chris fellows

    #1

    Type conversion

    I'm using a third party .NET 2 DLL from VB.NET and I'm am setting a property
    of type 'int'. However, if I set a value larger than a 'short' (32k) then
    reading the property back returns a negative number. Can someone tell me
    what is likely to be happening within the property procedure that would
    cause this? (The property should just be storing the value but appears to be
    doing something unintentionally .)

    I have a SQL stored proc that receives the negative value and, as a
    temporary bug fix, I want to be able to reverse the procedure to get back to
    the original number. I appreciate that a narrowing conversion has probably
    occured so its possible that I can't get back to the original number.


  • Jon Skeet [C# MVP]

    #2
    Re: Type conversion

    chris fellows <chrisfellows@n ospam.co.ukwrot e:
    I'm using a third party .NET 2 DLL from VB.NET and I'm am setting a property
    of type 'int'. However, if I set a value larger than a 'short' (32k) then
    reading the property back returns a negative number. Can someone tell me
    what is likely to be happening within the property procedure that would
    cause this? (The property should just be storing the value but appears to be
    doing something unintentionally .)
    I suspect it's being converted to a short behind the scenes, whether
    intentionally or not.
    I have a SQL stored proc that receives the negative value and, as a
    temporary bug fix, I want to be able to reverse the procedure to get back to
    the original number. I appreciate that a narrowing conversion has probably
    occured so its possible that I can't get back to the original number.
    Well exactly. In C# you could cast from int to ushort, then back to int
    again... for instance:

    using System;

    public class Test
    {
    static short dodgy;

    public static int Dodgy
    {
    get { return dodgy; }
    set { dodgy = (short) value; }
    }

    public static int SlightlyDodgy
    {
    get { return (ushort) Dodgy; }
    set { Dodgy = value; }
    }

    public static void Main()
    {
    Dodgy = 60000;
    Console.WriteLi ne (Dodgy);
    Console.WriteLi ne (SlightlyDodgy) ;
    }
    }

    However, that won't work for numbers over 65535. What happens when you
    set the property to, say, 100000?

    --
    Jon Skeet - <skeet@pobox.co m>
    http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
    If replying to the group, please do not mail me too

    Comment

    Working...