How to create type safe enums?

It is possible to achieve this with a few tricks. Given typedef enum { BLUE, RED } color_t; Then define a dummy union which won’t be used by the caller, but contains members with the same names as the enumeration constants: typedef union { color_t BLUE; color_t RED; } typesafe_color_t; This is possible because enumeration … Read more

Which Typesafe Enum in C++ Are You Using?

I’m currently playing around with the Boost.Enum proposal from the Boost Vault (filename enum_rev4.6.zip). Although it was never officially submitted for inclusion into Boost, it’s useable as-is. (Documentation is lacking but is made up for by clear source code and good tests.) Boost.Enum lets you declare an enum like this: BOOST_ENUM_VALUES(Level, const char*, (Abort)(“unrecoverable problem”) … Read more

Discriminated union in C#

I don’t really like the type-checking and type-casting solutions provided above, so here’s 100% type-safe union which will throw compilation errors if you attempt to use the wrong datatype: using System; namespace Juliet { class Program { static void Main(string[] args) { Union3<int, char, string>[] unions = new Union3<int,char,string>[] { new Union3<int, char, string>.Case1(5), new … Read more

How to make Databinding type safe and support refactoring?

Note this answer uses WinForm and was written before C# had ‘NameOf()’ Thanks to Oliver for getting me started I now have a solution that both supports refactoring and is type safe. It also let me implement INotifyPropertyChanged so it copes with properties being renamed. It’s usage looks like: checkBoxCanEdit.Bind(c => c.Checked, person, p => … Read more

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language? A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the … Read more

Type safety: Unchecked cast

The problem is that a cast is a runtime check – but due to type erasure, at runtime there’s actually no difference between a HashMap<String,String> and HashMap<Foo,Bar> for any other Foo and Bar. Use @SuppressWarnings(“unchecked”) and hold your nose. Oh, and campaign for reified generics in Java 🙂