Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trouble with casting
Message
De
23/09/2014 12:52:13
 
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Application:
Web
Divers
Thread ID:
01608054
Message ID:
01608076
Vues:
28
This message has been marked as the solution to the initial question of the thread.
J'aime (1)
>>>>Hi everybody,
>>>>
>>>>Do you see why this very simple code gives me trouble?
>>>>
>>>>
>>>>var lastLocSuffix = _salespointAdapter.GetAll().Select(sp => new { LocSuffix = sp.LocSuffix }).OrderByDescending(sp => sp.LocSuffix).FirstOrDefault();
>>>>            Int16 newSuffix = 1;
>>>>            if (lastLocSuffix != null)                
>>>>                newSuffix = Convert.ToInt16(lastLocSuffix) + newSuffix; // Doesn't like this line
>>>>
>>>>            salespoint.LocSuffix = newSuffix; 
>>>>
>>>>
>>>>I am trying to increment a number by 1. The number is supposed to be short. Why does it say something about cast if I declared the number to be short?
>>>>
>>>>What am I missing in this code?
>>>>
>>>>Thanks in advance.
>>>
>>>What is the value of lastLocSuffix? Can it be converted to a short?
>>>
>>>Also you can probably replace your Select, OrderByDescending, and FirstOrDefault with just Max.
>>
>>Ok, two lines code works fine
>>
>>
>>   newSuffix = Convert.ToInt16(lastLocSuffix);
>>                newSuffix++;
>>
>>Why one line doesn't work, I don't know.
>
>
>It doesn't work because the compiler knows that when you add 2 shorts together you could overflow (so it needs an int/Int32 to store the result). It wants you to specifically cast the result of the addition to a (short) before it gets assigned to newSuffix so it knows that you understand the consequences that you could possibly lose data. If you want it as one line:
>
>
>newSuffix = Convert.ToInt16(lastLocSuffix) + 1;
>
Adding two ints could overflow to a long, so that probably isn't a good argument. Based on http://stackoverflow.com/questions/11853602/c-sharp-does-not-let-me-sum-two-shorts-to-a-short, it looks like there is no + operator assigned for shorts, so they get promoted to ints, and the result is therefore an int.
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform