0

I need an array of the same dimensions (to hold values 0 or 1) as an argument to a function which may be of any rank and any type. The result array will contain 0 for failure and 1 for success (I could use Boolean) arising from a process. How can I create the result array?

3
  • What is the specific requirement? Did you try anything? Creating a boolean array of a specific size maybe? Commented Oct 4, 2015 at 20:20
  • This seems like an insane requirement. For failure, you should throw an exception. Commented Oct 4, 2015 at 20:30
  • @IanNewson: It's not insane. There are times when you have a list of things you want to do, and you want to report which of them could be done. Exceptions are often the best solution for failure situations, but not always. Commented Oct 4, 2015 at 20:36

1 Answer 1

5

Use Array.CreateInstance:

private static Array CreateArray(Array array)
{
    List<int> dimensions = new List<int>();
    for (int i = 0; i < array.Rank; i++)
    {
        dimensions.Add(array.GetLength(i));
    }
    return Array.CreateInstance(typeof(bool), dimensions.ToArray());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Exactly what I was searching for (for several hours!). Thank you very much.
If this is the solution to your problem mark it as such so the other people would know :]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.