References and Pointers, Part Two

Here’s a handy type I whipped up when I was translating some complex pointer-manipulation code from C to C#. It lets you make a safe “managed pointer” to the interior of an array. You get all the operations you can do on an unmanaged pointer: you can dereference it as an offset into an array,…


References and Pointers, Part One

Writing code in C# is really all about the programmatic manipulation of values. A value is either of a value type, like an integer or a decimal, or it’s a reference to an instance of a reference type, like a string or an exception. Values you manipulate always have a storage location that stores the…


Why is covariance of value-typed arrays inconsistent?

Another interesting question from StackOverflow: uint[] foo = new uint[10];object bar = foo;Console.WriteLine(“{0} {1} {2} {3}”,          foo is uint[], // True  foo is int[],  // False  bar is uint[], // True  bar is int[]); // True What the heck is going on here? This program fragment illustrates an interesting and unfortunate inconsistency between the CLI type system and…


Arrays of arrays

Most people understand that there’s a difference between a “rectangular” and a “ragged” two-dimensional array. int[,] rectangle = {   {10, 20},   {30, 40},   {50, 60} };int[][] ragged = {   new[] {10},   new[] {20, 30},   new[] {40, 50, 60} }; Here we have a two-dimensional array with six elements, arranged…


Arrays considered somewhat harmful

I got a moral question from an author of programming language textbooks the other day requesting my opinions on whether or not beginner programmers should be taught how to use arrays. Rather than actually answer that question, I gave him a long list of my opinions about arrays, how I use arrays, how we expect arrays to be…


Covariance and Contravariance in C#, Part Two: Array Covariance

C# implements variance in two ways. Today, the broken way. Ever since C# 1.0, arrays where the element type is a reference type are covariant. This is perfectly legal: Animal[] animals = new Giraffe[10]; Since Giraffe is smaller than Animal, and “make an array of” is a covariant operation on types, Giraffe[] is smaller than…


Running Me Ragged

  A reader asked “Why are there two types of multidimentional arrays? What is the difference between the (x)(y) and (x,y) notation?”   Good question.  There are two kinds of multidimensional arrays, called “rectangular” and “ragged“.  A rectangular array is, well, rectangular.  You say   DIm MyArrary(3,2)   and you get an array with indices:…


JScript and VBScript Arrays

    Earlier I alluded to the fact that JScript arrays are objects but VBScript arrays are not.  What’s up with that?   It’s kind of strange.  Consider the properties of a JScript array.  A Jscript array is   * one dimensional. * associative; JScript arrays are indexed by strings.  Numeric indices are actually converted…