Feeds:
Posts
Comments

Archive for October, 2010

I got asked this in one of my article forums, and thought I’d blog about it here so I can just direct people to a single URL if the question comes up again. Here’s how you’d do it (I used the example property the OP used):

//The header file

ref class Test
{
public:
  property Byte default[int]
  {
    Byte get(int index);
    void set(int index, Byte value);
  }

  //...
};

//The cpp file

Byte Test::default::get(int index)
{
  return 0;
}

void Test::default::set(int index, Byte value)
{
}

//...

Read Full Post »

This question was posted recently on the CodeProject forums. The OP wanted to know why this code would not compile (I’ve simplified it):

private void FooInternal(object[] values)
{
}

private void Foo<T>(T[] values)
{
    FooInternal(values);
}

The error thrown is:

Error	2	Argument 1: cannot convert from 'T[]' to 'object[]'

The fix is to add a constraint:

private void Foo<T>(T[] values) where T:class
{
    FooInternal(values);
}

If you are wondering why that is needed, consider this code snippet:

struct S
{
}

static void Main(string[] args)
{
    object[] arr = new S[10];
}

That won’t compile either. The reason’s that each of those value type members need to be boxed into an object to get an object array, meaning it’s now a different array. Since that is not standard behavior for casts, the compiler will not automatically do that for you (which is a good thing). If you did it manually, this is what it’d look like:

object[] arr = new S[10].Cast<object>().ToArray();

Read Full Post »

Follow

Get every new post delivered to your Inbox.