Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specified cast is not valid in Xamarin Forms

Does anyone know what happens when getting an error like Specified cast is not valid? I commented on the line where the error happens

private async void GetEmployee()
 {
     var _token = await GetAccessToken();            
     using (var _client = new HttpClient())
     {
         var _uri = "domain here";

         _client.BaseAddress = new Uri(_uri);
         _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);

         var _response = await _client.GetAsync("endpoint here'");

         var Emp = JsonConvert.DeserializeObject<Employee>(await _response.Content.ReadAsStringAsync());
         Employee = new ObservableCollection<Employee>((IEnumerable<Employee>)Emp); //Im having error on this line
     }
 }

 ObservableCollection<Employee> _employee;
 public ObservableCollection<Employee> Employee
 {
     get
     {
         return _employee;
     }
     set
     {
         _employee = value;
         OnPropertyChanged();
     }
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How about changing this:

Employee = new ObservableCollection<Employee>((IEnumerable<Employee>)Emp);

to this:

Employee = new ObservableCollection<Employee>(new[] {Emp});

See .NET Fiddle example.

See ObservableCollection documentation.


The new[] { ... } is short for new Employee[] { ... } and creates a new array with the initial value(s) inside the { and }.

See array documentation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading