Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

942
Views
C#: Unable to cast object of type 'System.Int64' to type 'System.Int32'

I have code as follows:

Dictionary<object, object> dict = ...
Color = (int)dict.GetValue("color");

When I convert the Color to an int, I get the following exception:

System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.

I am not sure why I can't just cast from a long to an int. I know for a fact that the value is less than 0xFFFFFF (24 bits) since it is a color.

I tried using unchecked but that didn't help either.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You must first unbox the value as the dictionary's value type is object.

Dictionary<object, object> dict = ...
Color = (int)(long)dict.GetValue("color");
over 4 years ago · Santiago Trujillo Report

0

If you don't know the original type, the following idiom may be more convenient.

public T Get<T>(string key)
{
    return (T) Convert.ChangeType(_dict[key], typeof(T), CultureInfo.InvariantCulture);
}
over 4 years ago · Santiago Trujillo Report

0

cannot be tracked because another instance with the same key value for is already being tracked

find solution

  context.Patrol.AddRange(model);  // error

entity.Property(e => e.Id)
                    .HasColumnName("ID")
                    .ValueGeneratedNever(); // old

entity.Property(e => e.Id)
                    .HasColumnName("ID"); //remove ValueGeneratedNever()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!