C
C#7mo ago
ByGoalZ

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
Jimmacle
Jimmacle7mo ago
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 collections
Becquerel
Becquerel7mo ago
you can, incidentally, use the [] syntax on other classes, if they define an 'indexer' for themselves
Becquerel
Becquerel7mo ago
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.
Jimmacle
Jimmacle7mo ago
yeah, though that's indexers and not the syntax used to instantiate the type
Becquerel
Becquerel7mo ago
very true, my bad
ByGoalZ
ByGoalZOP7mo ago
Thanks, and what are the brackets for?
Jimmacle
Jimmacle7mo ago
for which syntax? declaring the array? that's just how arrays are specified
ByGoalZ
ByGoalZOP7mo ago
no for the stack Stack<int> stack = new Stack<int>(); the brackets at the end
Jimmacle
Jimmacle7mo ago
i explained in the second message
ByGoalZ
ByGoalZOP7mo ago
Yea but I mean those (), not <>
Jimmacle
Jimmacle7mo ago
those are parentheses and that's how you instantiate classes, you're calling the class constructor which may or may not have arguments
ByGoalZ
ByGoalZOP7mo ago
oh alright. Thank you. Didnt know those were classes
Jimmacle
Jimmacle7mo ago
most things are, even arrays but they just have special syntax
Want results from more Discord servers?
Add your server