Home > Software engineering >  Specified cast is not valid in Xamarin Forms
Specified cast is not valid in Xamarin Forms

Time:12-08

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();
     }
 }

CodePudding user response:

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.

  • Related