C# Basics – Object Arrays – Part 13

We get to know how to use object arrays in C# programming language. We can create custom data type or object and use it in an array.


Andraz Krzisnik
C# Basics – Object Arrays – Part...

Object Arrays

We already mentioned before, that when we create a class we create an object with custom data type.

So, as you can see, like strings, integers and other data types, we can create arrays of these custom data types as well.

For example:

public class Rabbit
{
    public string serial;
    public bool gender;
    public double mass;
}

For the sake of simplicity, we won’t add any constructors.

Now let’s say we have 200 of these objects and what we want is to process every single one the same way. We do that by creating an array, that can store such data type.

Rabbit[] arrRabbit;

Here we have an example of how object arrays might be used.

Rabbit[] r = new Rabbit[250];
int i = 0;
int group = 10;
string s = "";
while (i < group)
{
    r[i] = new Rabbit();
    r[i].serial = "16548";
    r[i].gender = false;
    r[i].mass = 0.20;
    i++;
}
for (int j = 0; j < group; j++)
{

    s += "Serial: " + r[j].serial + ", Gender: " + (r[j].gender == false ? "Female" : "Male") + ", Mass: " + r[j].mass + Environment.NewLine;
}
MessageBox.Show(s);
Download Examples Next Chapter
Show Comments (0)

Comments

Related Articles

C# Tutorial

C# Tutorial: How To Apply Dilation To An Image

Dilation is a simple morphology process which changes pixel intensities based on the change of intensities that occur at object boundaries. This process is used on grayscale...

Posted on by Andraz Krzisnik
C# Basics

C# Basics – Arrays – Part 8

Arrays It’s an often occurrence, that we are dealing with a bunch of data of the same data type. And in case we want to process each value in the same or similar way, arrays come...

Posted on by Andraz Krzisnik