0

i hope that you can help. i was searching through the whole internet to get an answer but i couldn´t find one. i am a beginner in C# and the .NET Framework and i am recently working with an API to fetch some Data about movies and also to learn how to work with APIs in general.

I am using the MVVM Pattern to accomplish my goals.

So, i´ve implemented the httpClient in a Class and i created a model class for the fetched data. Now when i Invoke the Method e.g. in a ViewModel to initialize a new Object of the model class, the IDE tells me that i cannot convert type Tasks.Task "model class" to "model class".

I hope the code example makes it more clear what i am trying to explain:

public class MovieDatabase
    {
        private static readonly HttpClient httpClient = new HttpClient();
        public static async Task<MovieDatabaseResponse> GetDataAsync()
        {

            try
            {
                string finalQuery = $@"https://api.themoviedb.org/3/movie/550?api_key={ApiKey}&language=de-DE";

                string responseBody = await httpClient.GetStringAsync(finalQuery);

                MovieDatabaseResponse? movieDatabaseResponse = JsonConvert.DeserializeObject<MovieDatabaseResponse>(responseBody);

                return movieDatabaseResponse;

            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);

                MovieDatabaseResponse? emptyresponse = null;

                return emptyresponse;
            }
        }
    }
    public class MovieDatabaseResponse
    {
        public string title;
        public string overview;
        public string tagline;
    }
        public MainWindow()
        {
            InitializeComponent();

            MovieDatabaseResponse theResponseObject = MovieDatabase.GetDataAsync();

            
        }

I've made the GetDataAsync() method static just to test it fast in the mainWindow because I didn´t build the pattern/architecture properly yet.

Thanks in advance, guys!

I've tried to put it in a var variable but the debugger told me that it wasn't yet computed.

Narish
  • 607
  • 4
  • 18
Patrick
  • 1
  • 2
  • `GetDataAsync()`  returns a `Task` and you're trying to shove that into a `MovieDatabaseResponse` variable. But since you're doing that in a constructor, you can't just `await` it like you did with `httpClient.GetStringAsync(finalQuery)`. [This answer might give you a few pointers on how to handle this](https://stackoverflow.com/a/23051370/71141). – Etienne de Martel May 04 '23 at 03:47
  • 1
    @Narish thanks for your edit. pretty inattentive from me. – Patrick May 04 '23 at 12:19
  • @EtiennedeMartel thanks for your reply and it really helped. Especially the Async OOP Series https://blog.stephencleary.com/2013/01/async-oop-0-introduction.html has great insights. So what i understand is that async Constructors are simply not allowed and i have some to take another approach e.g. the Factory Pattern to work with the results properly. If i would call the function in the constructor the async function doesnt have a proper caller to handle the function, am i right? – Patrick May 04 '23 at 12:25
  • @Patrick no problem! Always be careful...Now onto your main question itself, I see that when you catch an exception you are returning `null` but that should mean that your method return type is `Task`. As such, your `MainWindow()` method should be `async` and should contain `MovieDatabaseResponse? theResponseObject = await MovieDatabase.GetDataAsync();` followed by maybe some validation code like `if (theResponseObject is null) { //do something here }` – Narish May 04 '23 at 13:48
  • Try out those changes and see if it resolves the error. If not, please edit your post and include the exact error message so we can properly diagnose what is the issue here – Narish May 04 '23 at 13:49
  • `MyObject?` is the same as saying `Nullable` which will *never* be the same typing as `MyObject`. So you need to unwrap and validate accordingly when working with nullable types – Narish May 04 '23 at 13:51
  • @Narish `MainWindow()`  is a constructor, you can't just make it async. – Etienne de Martel May 04 '23 at 15:05
  • @Narish Also, `MyObject?` will only be `Nullable` if `MyObject` is a value type, which is not the case here as `MovieDatabaseResponse` is a reference type. This uses [nullable reference types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references). – Etienne de Martel May 04 '23 at 15:11
  • Ah didn't realize it was a constructor. But your second comment depends on context. In the newer versions of .NET (core), unless you deliberately turn on nullable references for the project you will still be required to declare nullable reference types as `MyObject?` and personally I think that is for the better – Narish May 04 '23 at 15:24
  • Using async anything in a constructor is a tricky situations, [this](https://stackoverflow.com/questions/8145479/can-constructors-be-async) may be helpful – Narish May 04 '23 at 15:26

0 Answers0