Skip to content

Instantly share code, notes, and snippets.

@mattumotu
Created December 3, 2018 13:50

Revisions

  1. mattumotu created this gist Dec 3, 2018.
    12 changes: 12 additions & 0 deletions generics-unboxing.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    IFetchThings fetcher = new ClientFetcher();
    object fetched = fetcher.Fetch(); // object is really a Client (Boxed as an object)

    // let's convert the object to a client
    Client c = (Client)fetched; // Unbox fetched into Client - performance hit
    // the compiler can't see any problem with this
    // and it works at run-time

    // let's convert the object to a project
    Project p = (project)fetched; // Unbox fetched into Project - performance hit
    // the compiler can't see a problem with this
    // but when it runs you get an InvalidCastException - Whoops