0

I can't understand why the object is null right after I instantiate it. Exception occurs at _homeViewModel.ApiToken.Token.Id = token.Id;. _homeViewModel.ApiToken is not null.

public class GetTokenInfoCommand : AsyncCommandBase
{
    private HomeViewModel _homeViewModel;
    private readonly ITokenService _tokenService;

    public GetTokenInfoCommand(HomeViewModel homeViewModel, ITokenService tokenService)
    {
        _homeViewModel = homeViewModel;
        _tokenService = tokenService;
    }

    public override async Task ExecuteAsync(object parameter)
    {
        var token = await _tokenService.GetTokenInfo(_homeViewModel.ApiKey);
        _homeViewModel.ApiToken.Token = new Token();
        _homeViewModel.ApiToken.Token.Id = token.Id;
    }
}

Here's HomeViewModel class:

    public class HomeViewModel : ViewModelBase
    {
        private UserPreferences _userPreferences;

        private ApiToken _apiToken;
        public ApiToken ApiToken
        {
            get => _apiToken ?? new ApiToken();
            set
            {
                _apiToken = value;
                OnPropertyChanged(nameof(ApiToken));
            }
        }

        public ICommand GetTokenInfoCommand { get; }
        
        public HomeViewModel(UserPreferences userPreferences, ITokenService tokenService)
        {
            _userPreferences = userPreferences;
            _apiKey = _userPreferences.ApiKey;
            
            GetTokenInfoCommand = new GetTokenInfoCommand(this, tokenService);
        }
    }

And ApiToken class:

    public class ApiToken
    {
        private Token _token;
        public Token Token
        {
            get => _token;
            set
            {
                _token = value;
            }
        }
    }

The GetTokenInfoCommand is called through a button: <Button Content="GO" Command="{Binding GetTokenInfoCommand}"/>

What may be happening here? Any suggestions on how to solve this?

Clemens
  • 123,504
  • 12
  • 155
  • 268
Marcelo
  • 5
  • 4
  • 1
    The `ApiToken` property getter is broken. As long as the backing field is null, it always returns a new ApiToken instance. Setting the Token of one ApiToken has no effect on the next ApiToken returned by the getter. The getter should look like this `get => _apiToken ?? (_apiToken = new ApiToken());` – Clemens Nov 09 '20 at 18:08
  • That was the problem indeed. Thanks, @Clemens! – Marcelo Nov 09 '20 at 18:31
  • you can further simplify the getter in c#8 get => _apiToken ??= new ApiToken(); – Athul Raj Nov 10 '20 at 12:32

0 Answers0