-
Notifications
You must be signed in to change notification settings - Fork 18
Extracting data from posts
Let's say you already have a static class Tumblr that has a Client that you can call API methods from. In this case, we have a variable "posts" that contains the result of a GetPostsAsync call.
How can we use the data from our GetPostsAsync method? Because posts can contain different properties based on their PostType, we're going to need to loop over our array and cast each post to the proper type before we can use special properties.
Without casting, we can only access data that is guaranteed to exist. These are the properties on a BasePost.
// get the ID of the first post
var id = posts[0].Id;
// works fine! All post types have an Id, so no casting is needed.// get the Audio source from an Audio post
var audio = posts[0].AudioUrl
// Fails! This property does not exist for all posts. We need to cast our object before we can use itWe can use a switch to do the latter efficiently.
for (var i = 0; i < posts.Length; i++)
{
// convenient to set `posts[i]` to var post
var post = posts[i];
switch (post.Type)
{
case PostType.Answer:
doSomething((AnswerPost)post);
break;
case PostType.Audio:
doSomething((AudioPost)post);
break;
// etc...
}
}Within that switch statement we can cast and use all properties of each post, now that we know their specific type. For example, to get the AudioUrl from the problem above, we'd simply do the following within our switch:
case PostType.Audio:
// cast our post
var post = (AudioPost)post;
var audioUrl = post.AudioUrl;Of course, in the real world you would most likely want to consolidate logic into a function and then call that function from the switch case statement. For this, I recommend using an overloaded function that takes each post type.