FlatSharp v3.2.0 Release Notes

Release Date: 2020-07-31 // over 3 years ago
  • ๐Ÿš€ It's been awhile, but FlatSharp has a new release out with support for better unions when using FBS files. So what's new?

    ๐Ÿš€ Let's talk about the problem with unions in prior releases using this FBS schema as our guide:

    table Dog { ... }
    table Cat { ... }
    table Fish { ... }
    
    union FavoritePet { Dog, Cat, Fish }
    
    table Person { FavoritePet:FavoritePet; }
    

    You'd get some code that looked like this:

    [FlatBufferTable]public class Person : object{ [FlatBufferItem(0)] public virtual FlatBufferUnion\<Dog, Cat, Fish\> FavoritePet { get; set; } }
    

    In short, you declared a FlatBufferUnion{T} instance and used the generic parameters of that type to call out the members of the union. When interacting with it, code often looked like this:

    Person p = (...)Dog dog = p.FavoritePet.Item1; // Unintuitive.switch (p.FavoritePet.Discriminator) { case 1: // What does 1 mean?Console.WriteLine("dog"); break; case 2: // catConsole.WriteLine("cat"); break; case 3: default: Console.WriteLine("fish"); break; }
    

    However, simply using a generic type supplied by FlatSharp wasn't very useful because it made the code harder to read. Item1 is just not a good description. The other big problem is a union that has many members. Imagine trying to plumb FlatBufferUnion<T1,...,T10> through your code.

    In version 3.2.0, FlatSharp will generate custom union classes for you when using FBS schemas. In this example, you'd get a FavoritePet class that looks like this:

    public class FavoritePet : FlatBufferUnion\<Dog, Cat, Fish\> { public enum ItemKind : byte { Dog = 1, Cat = 2, Fish = 3, } public ItemKind Kind { get; } public Dog Dog { get; } public Cat Cat { get; } public Fish Fish { get; } }
    

    ๐Ÿ— This should greatly increase the usability of unions. The final change is a set of methods that have been added to all Union types called Switch. The methods are semantically the same as a switch statement, but with compiler support so you'll get build breaks when a new item is added to the union. This is handy because it ensures that you explicitly address all cases in your code where the new union member could occur. Catching errors at build time is better than runtime!

    FavoritePet pet = person.Pet;string petSays = pet.Switch( caseDefault: () =\> "??", caseDog: () =\> "Woof", caseCat: () =\> "Meow", caseFish: () =\> "gurgle gurgle");