Newbie question: Decleration of stack vs Arrays
Hello,
so I know the basics of C# but one thing I never understood or learned was how data structures are being created/declared
So there are like 3+ ways of declaring an array, I typically use:
String[] example = new string[3];
(First question: What is new for? Why is it being used here?)
And today I learned stacks but they are declared differently:
Stack<int> stack = new Stack<int>();
So why is that? Why isnt it
Stack[int] stack = new Stack; And what are the brackets for
13 Replies
new is used because you're creating an instance of an object, the reason arrays use
type[]
and other collections use CollectionType<type>
is because arrays are special and all other collections are implemented as generic classes
the things between the <>
are generic type arguments, basically a way to specialize a class for specific types and aren't limited to being used for collectionsyou can, incidentally, use the [] syntax on other classes, if they define an 'indexer' for themselves
Indexers - C# Programming Guide - C#
Indexers in C# allow class or struct instances to be indexed like arrays. You can set or get the indexed value without specifying a type or instance member.
yeah, though that's indexers and not the syntax used to instantiate the type
very true, my bad
Thanks, and what are the brackets for?
for which syntax? declaring the array? that's just how arrays are specified
no for the stack
Stack<int> stack = new Stack<int>();
the brackets at the end
i explained in the second message
Yea but I mean those (), not <>
those are parentheses
and that's how you instantiate classes, you're calling the class constructor which may or may not have arguments
oh alright. Thank you. Didnt know those were classes
most things are, even arrays but they just have special syntax