C # convert int to int64

we are in the process of updating our crappy cms system and the new builds have changed from int to int64. I am having a problem trying to build now. I tried casting but it doesn't seem to help. here is one piece of code that causes the problem.

IDictionary<int, string> aliases = new UrlAliasApi().GetUrlAliasesByType( Company.DataLayer.Enumeration.UrlAliasType.Recipe); foreach (ContentBase recipe in mergedResultset) { // if alias exists, overwrite quicklink! string alias; if (aliases.TryGetValue(recipe.Id, out alias)) { recipe.QuickLink = alias; } } 

Error

Error 323 The best overloaded method match for 'System.Collections.Generic.IDictionary.TryGetValue (int, out string)' has some invalid arguments

Referring to recipe.Id , which is an Int64 value.

Any ideas to solve this problem?

+4
source share
5 answers

Since C # is strongly typed, you cannot convert like this. You need to enable Int64 in Int32 before passing it:

 aliases.TryGetValue((int)recipe.Id, out alias) 

Alternatively, you can change the definition of the dictionary:

 IDictionary<Int64, string> aliases = new UrlAliasApi().GetUrlAliasesByType(Company.DataLayer.Enumeration.UrlAliasType.Recipe) .ToDictionary(kvp => (Int64)key.Key, kvp => kvp.Value); 
+2
source

You need to pass Int64 to int , for example:

 aliases.TryGetValue((int)recipe.Id, out alias) 
+1
source

The problem is that you are trying to use an Int64 value in a place that takes an int/Int32 . There is no implicit conversion, and therefore no compiler errors.

The best way to fix this is to convert the aliases dictionary to use the Int64 type. It is always safe to convert int to Int64 , so there is no loss of information in this conversion.

Ideally, you convert GetUrlAliasesByType to return an IDictionary<Int64,string> . The rest of the system now uses Int64 , so this conversion makes sense. Otherwise, you can do the following

 string alias; try { if (aliases.TryGetValue(checked((int)recipe.Id), out alias)) { recipe.QuickLink = alias; } } catch (OverflowException) { // id not valid } 

A proven operation is necessary here because it prevents inactive overflow from creating a false match using TryGetValue

+1
source

Note that although you can use Int64 for Int32 (or int), you may lose some data if the values ​​you execute are larger than what Int32 can represent. In your case, this may not matter, but I thought I should mention this.

+1
source

Why can't you use Dictionary<Int64, string> instead of Dictionary<int, string> ?

0
source

All Articles