#1,059 – Converting from Numeric to Enumerated Types

You can convert from a numeric type to an enumerated type using the cast operator.  For example, to convert from numeric constants to an enum, we can do the following:

        public enum Weekday
            Sunday = 1,
            Monday,     // 2
            Tuesday,    // 3, etc.

        static void Main(string[] args)
            Weekday day = (Weekday)5;  // Thursday
            Console.WriteLine(day.ToString());  // "Thursday"

            Weekday day2 = (Weekday)8;    // Works!
            Console.WriteLine(day2.ToString());  // Just "8"

Notice that the cast works even if there is not a defined enumerated value that matches the specified type. We can store a value of 8 in a Weekday type even though we didn’t define a Weekday with a value of 8.



#447 – Use as Operator to Get At an Object’s Interfaces

If a class implements an interface, you can assign a variable whose type is that class directly to a variable of the interface’s type.

            Cow bossie = new Cow("Bossie", 12);

            IMoo viaMoo = bossie;

However, there might be times when you have a variable of a more general type and the variable may or may not implement a particular interface. In these cases, you could use a dynamic cast to cast the object variable to the interface type.

            object objSomething = bossie;

            // Can't assign directly; need cast
            IMoo viaMoo = (IMoo)objSomething;

The only problem is that this cast will fail, throwing an InvalidCastException, if the object does not implement IMoo.  Instead, you can use the as operator, which essentially does the cast, but just returns null if the cast fails.

            IMoo viaMoo = objSomething as IMoo;
            if (viaMoo != null)