#1,199 – Equality and Inequality with Nullable Types

The equality and inequality operators work with nullable types as follows:

  • If both operands are non-null, the operators are applied to the values
  • If one operand is null and the other has a value, == returns false, != returns true
  • If both operands are null, == returns true and != returns false
            int? val1 = 5;
            int? val2 = 10;
            int? val3 = null;
            int? val4 = null;
            int? val5 = 10;

            bool b1 = val1 == val2;   // False
            b1 = val2 == val5;        // True
            b1 = val1 == val3;        // False
            b1 = val1 != val3;        // True
            b1 = val3 == val4;        // True
            b1 = val3 != val4;        // False

#1,198 – Using Operators with Nullable Types

When using a nullable type, you can use the operators with the nullable type that are associated with the underlying value type.

The example below shows how we can use the < and > operators with the int? type.  They work as they would work with the int type itself, for non-null values.

            int? val1 = 5;
            int? val2 = 10;

            bool b1 = val1 < val2;   // True

If one of the two values is null, the expression will evaluate to false, regardless of the other value.

            val2 = null;
            b1 = val1 < val2;    // False
            b1 = val2 < val1;    // False
            b1 = val1 == val2;   // False

#1,111 – Converting an Integer to a String in a Different Base

You can convert an integer-based value to a string using the ToString method on the integer.  This results in a string representing the integer as a base 10 number.

            int i = 42;
            // ToString() called implicitly
            Console.WriteLine(i);  // base 10

1111-001

You can also convert integer-based values to strings that represent the number in base 2 (binary), 8 (octal), or 16 (hexadecimal).  You use the Convert.ToString method, passing it the number to convert and the base.

            int i = 42;
            int i2 = 1964;
            int i3 = -128;

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i,
                Convert.ToString(i, 16),
                Convert.ToString(i, 8),
                Convert.ToString(i, 2));

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i2,
                Convert.ToString(i2, 16),
                Convert.ToString(i2, 8),
                Convert.ToString(i2, 2));

            Console.WriteLine("{0} dec, {1} hex, {2} oct, {3} bin",
                i3,
                Convert.ToString(i3, 16),
                Convert.ToString(i3, 8),
                Convert.ToString(i3, 2));

1111-002

#1,076 – Implicit Numeric Conversions from the char Type

You can implicitly convert an instance of a char to any of the following numeric types:

ushort int, uint, longulong, float, double, or decimal

When you implicitly convert a char to a numeric value, you use the associated code point as the numeric value.  Because of this implicit conversion, you can use char instances within numeric expressions.  Below are some examples:

            int n = 'a';  // 97
            char c1 = 'a';
            n = c1;  // still 97

            char c2 = '\u1820';
            int n2 = c2;  // 6176 (0x1820)

            int delta = 'd' - 'a';  // 3
            int strangeSum = 'a' + 'b';  // 97 + 98 = 195

#1,066 – Constraining a Type Parameter on a Generic Interface

You can constrain a type parameter on a generic interface so that it can be used only as the output type of methods in the interface and not as a type of any method parameters.  You do this using the out keyword on the type parameter.

        public interface FirstAndLast<out T>
        {
            T First();
            T Last();
            void AddThing(T item);   // won't compile
        }

This seems like an odd thing to do, but ensuring that a particular type parameter is used only as output allows us to later use this generic interface covariantly.  (I’ll explain this in an upcoming post).

#1,065 – Cases When Array Covariance Doesn’t Work

Array covariance in C# allows you to assign an array of objects of a more derived type to an array of objects of a base type.  An array of type B can be assigned to an array of type A is type B is implicitly convertible to A.  More specifically, an implicit reference conversion from B to A must exist.

This restriction means that array covariance will not work for implicit conversions that are not implicit reference conversions.  Specifically, arrays are not covariant for implicit numeric conversions, boxing conversions or implicit custom conversions.

            // Covariance does work when implicit reference conversion
            // exists for underlying types
            //   - From S to T when S derives from T
            //   - From S to object or dynamic
            //   - From S to interface-type T when S implements T
            //   - From interface-type S to interface-type T when S derives from T
            // All examples below work (compile)
            Terrier[] tarr1 = new Terrier[2];
            Dog[] darr1 = tarr1;
            object[] oarr1 = tarr1;
            dynamic[] dynarr1 = tarr1;
            Dog[] darr2 = new Dog[2];
            IBark[] ibarr1 = darr2;
            IBarkBetter[] ibb1 = new IBarkBetter[2];
            IBark[] ibarr2 = ibb1;

            // Covariance does NOT work with implicit numeric conversions
            //  e.g. byte to short
            byte[] barr1 = new byte[2];
            short[] sarr1 = barr1;  // Compile-time error

            // Covariance does NOT work with implicit nullable conversions
            int[] inarr1 = new int[2];
            int?[] innarr1 = inarr1;  // Compile-time error

            // Covariance does NOT work with implicit boxing conversions
            int[] inarr2 = new int[2];
            object[] oarr2 = inarr2;  // Compile-time error

            // Covariance does NOT work with implicit custom conversions
            Cow c = new Cow("Bessie");
            Dog d = c;  // Implicit Cow to Dog works (custom conversion)
            Cow[] herd = new Cow[2];
            Dog[] pack = herd;  // Compile-time error

#1,064 – Getting Around Inability to Explicitly Convert Type Parameters

You can’t explicitly convert a type parameter to either a value type or a reference type (you can convert to an interface).

To get around this restriction, you can use the as operator on the type parameter.  This gives you a way to effectively convert the type parameter, get the code to compile, and avoid runtime exceptions.

    class Program
    {
        public class ThingContainer<T>
        {
            private T thing;

            public void SetThing(T t)
            {
                thing = t;

                // Won't compile
                //int i = (int)t;

                // Do this instead
                int? i = t as int?;
                if (i.HasValue)
                    Console.WriteLine("Your int: " + i);

                // Won't compile
                //Dog d = (Dog)t;

                // Do this instead
                Dog d = t as Dog;
                if (d != null)
                    Console.WriteLine("Your Dog: " + d.Name);
            }
        }

        static void Main(string[] args)
        {
            ThingContainer<int> intcont = new ThingContainer<int>();
            intcont.SetThing(5);

            ThingContainer<Dog> dogcont = new ThingContainer<Dog>();
            dogcont.SetThing(new Dog("Bowser"));

            ThingContainer<Cow> cowcont = new ThingContainer<Cow>();
            cowcont.SetThing(new Cow("Bessie"));

            Console.ReadLine();
        }
    }

1064-001