0

While studying C#,I got the following doubt.Since arrays are reference types in C# when declared I think they are allocated on heap all the time.So when we declare array in following the ways:

int[] arr1 = {1,2,3};
int[] arr2 = new int[3] { 1, 2, 3 };

Is there any difference between them?

And can we declare array int arr[100]; like in C++?(without initializing and without using new keyword)And then assign them value later.

7
  • 3
    Just look at this Eric Lippert answer, it have been asked before Commented Jun 13, 2013 at 13:14
  • 2
    after this function returns you can still use arr2 What the heck are you talking about? Commented Jun 13, 2013 at 13:14
  • 1
    @bapusethi that is true in C++ not in C# i think Commented Jun 13, 2013 at 13:15
  • @bapusethi An array is a reference type, so it cannot be allocated on the stack. Commented Jun 13, 2013 at 13:15
  • @Pierre-LucPineault Thanks,I got the answer for the first question.can we declare int arr[100]; in C# like we do in C++?(or similar syntax) Commented Jun 13, 2013 at 13:23

1 Answer 1

0

Its the array initialization syntax

int[] arr1 = {1,2,3};
int[] arr2 = new int[3] { 1, 2, 3 };
int[] arr2 = new int[] { 1, 2, 3 };

they are the same. In this case...

int[] arr2 = new int[3] { 1, 2, 3 };

since you declared the size[3] after you must match the quantity.

check this tutorial http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

EDIT:

int[] MyArray = new int[100];
            int[] MyOtherArray = MyArray;

this is what you can do about your second question

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.