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.

ZoomIn
  • 1,237
  • 1
  • 17
  • 35
  • 3
    Just look at this [Eric Lippert answer](http://stackoverflow.com/a/5678393/2316200), it have been asked before – Pierre-Luc Pineault Jun 13 '13 at 13:14
  • 2
    `after this function returns you can still use arr2` What the heck are you talking about? – tnw Jun 13 '13 at 13:14
  • 1
    @bapusethi that is true in C++ not in C# i think – ZoomIn Jun 13 '13 at 13:15
  • @bapusethi An array is a reference type, so it cannot be allocated on the stack. – Ilya Kogan Jun 13 '13 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) – ZoomIn Jun 13 '13 at 13:23
  • No zoomln unfortunatly you cant,you can assign other array to your new one. – terrybozzio Jun 13 '13 at 13:28
  • C#, being a garbage collected language, allows you to *mostly* ignore memory allocation issues. There *are* some issues that are important to think about, but most of that is handled for you if you properly handle `IDisposable` subclasses with `using` statements. – Chris Pfohl Jun 13 '13 at 13:34

1 Answers1

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

terrybozzio
  • 4,424
  • 1
  • 19
  • 25