Difference between revisions of "Records"
(Created blank page) |
|||
Line 1: | Line 1: | ||
+ | =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: | ||
+ | |||
+ | <syntaxhighlight lang=c#> | ||
+ | struct Book | ||
+ | { | ||
+ | int ID; | ||
+ | string Title; | ||
+ | string Author; | ||
+ | double RetailPrice; | ||
+ | string Description; | ||
+ | int Edition; | ||
+ | bool Fiction; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This will need to go within your program, but NOT in any method or subroutine. You can now create an array of this: | ||
+ | |||
+ | <syntaxhighlight lang=c#> | ||
+ | Book[] collection = new Book[100]; | ||
+ | </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. : | ||
+ | |||
+ | <syntaxhighlight lang=c#> | ||
+ | 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; | ||
+ | </syntaxhighlight> |
Revision as of 10:50, 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. 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. :
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;