Difference between revisions of "Records"
(→Using your struct) |
|||
(One intermediate revision by the same user not shown) | |||
Line 20: | Line 20: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | This will need to go within your program, but NOT in any method or subroutine. You can now create an array of this: | + | This will need to go within your program, but NOT in any method or subroutine. |
+ | |||
+ | =Using your struct= | ||
+ | You can now create an array of this: | ||
<syntaxhighlight lang=c#> | <syntaxhighlight lang=c#> | ||
Line 26: | Line 29: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | You can then easily add a book to this structure by maintaining a variable called bookCount, which is incremented every time a book is added. : | + | You can then easily add a book to this structure by maintaining a variable called bookCount, which is incremented every time a book is added. Best practice is to create a temporary book and set the values, then to store this in the appropriate collections element: |
<syntaxhighlight lang=c#> | <syntaxhighlight lang=c#> |
Latest revision as of 10:52, 20 December 2018
Issues with Arrays
An array can only be of a single data type, for example and array of int or an array of string. This is because arrays are a data structure, they are an extension of the data types and are based upon the data type chosen.
However, you can essentially define your own type (Record) and then create an array of that instead.
Create a Record Structure
The command struct can be used to declare a new structure:
struct Book
{
int ID;
string Title;
string Author;
double RetailPrice;
string Description;
int Edition;
bool Fiction;
}
This will need to go within your program, but NOT in any method or subroutine.
Using your struct
You can now create an array of this:
Book[] collection = new Book[100];
You can then easily add a book to this structure by maintaining a variable called bookCount, which is incremented every time a book is added. Best practice is to create a temporary book and set the values, then to store this in the appropriate collections element:
Book temp = new Book;
temp.ID = 999;
temp.Title = "Black Mirror";
temp.Author = "Charlie Brooker";
temp.RetailPrice = 9.99;
temp.Description = "An view of the future";
temp.Edition = 1;
temp.Fiction = true;
collection[bookCount] = temp;