Conditionally declare fields for certain Android SDK versions?

MattHarringtonMattHarrington USMember, University

I'm aware of checking Android.OS.Build.Version.SdkInt to conditionally include code in methods. However, what's the best practice for conditionally declaring fields? For example:

public class StreamingService : Service
    MediaSession mediaSession; // How to conditionally declare this?

    public overrride OnCreate()
        if (Android.OS.Build.Version.SdkInt >= 21)
            // Do something with MediaSession, since it's only available in later SDKs

I believe MediaSession was introduced in API 21. What should I do about the field mediaSession? Declare it as Java.Lang.Object and then do a cast when I need to use it?

Thanks in advance,

Best Answer


  • MattHarringtonMattHarrington USMember, University

    Thanks for the tip. I incorrectly assumed the app would crash at runtime if I declared types not available on earlier Android versions. I suppose it only crashes if I use those types, not simply declare them.

Sign In or Register to comment.