CreateInstance question

  • Thread starter Thread starter > Adrian
  • Start date Start date
A

> Adrian

Array.CreateInstance( typeof(Int32), 5 );

What is the advantage of creating an array this way?

Adrian.
 
Hi Adrian,

It takes a Type as a parameter. This allows you to define an Array variable at design-time, and at
runtime create an instance of any given Type:

Array array = Array.CreateInstance(typeof(int), 5);

Since I hard-coded typeof(int) its value may not be as apparent, but imagine if a Type was passed
into a method instead, for instance, and used as the argument to the CreateInstance method.
 
Array provides the CreateInstance method, instead of public constructors, to
allow for late bound access.
 
Dave Sexton said:
Hi Adrian,
<snipped>
Since I hard-coded typeof(int) its value may not be as apparent, but imagine if a Type was passed
into a method instead, for instance, and used as the argument to the
CreateInstance method.

Apologies for being so slow: could you please give an example? I don't
follow.

Adriam
 
Hi Adrian,

public void DoStuff(Type arrayType)
{
// Here, Int32 is hard-coded
int[] intArray = null;

// Here, an Array of an unknown Type is created (late-bound)
Array unknownTypeArray = Array.CreateInstance(arrayType, 10);

// if we knew that arrayType was, for example, typeof(int)
// then we could cast our Array into an int[]:
if (unknownTypeArray is int[])
{
intArray = (int[]) unknownTypeArray;

Console.WriteLine("int[] length: " + intArray.Length);
}
else
Console.WriteLine("unknown Array Type: " + unknownTypeArray.GetType().FullName);
}
 
Dave, I played about with your example. Very interesting.
The point is clear now. Thank you,
Adrian.

using System;
public class SamplesArray
{
public static void Main()
{
Type arrayType = Type.GetType("System.String");
new SamplesArray().DoStuff(arrayType);
}

//public void DoStuff(Type arrayType)
public void DoStuff(Type arrayType)
{
// Here, Int32 is hard-coded
int[] intArray = null;

// Here, an Array of an unknown Type is created (late-bound)
Array unknownTypeArray = Array.CreateInstance(arrayType,5, 10);

// if we knew that arrayType was, for example, typeof(int)
// then we could cast our Array into an int[]:
if (unknownTypeArray is int[])
{
intArray = (int[]) unknownTypeArray;

Console.WriteLine("int[] length: " + intArray.Length);
Console.Read();
}
else
{
Console.WriteLine("unknown Array Type: " +
unknownTypeArray.GetType().FullName);
Console.Read();
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top