user1229895
user1229895

Reputation: 2319

Add a Count property to custom class in C#

So I have a custom class (ie, MyClass), which I then use to declare an array. How would I add a '.Count' property to my custom class to get the size of the array?

Thank you.

static void Main()
{
    MyClass[] test = new MyClass[2];
    test[0].str = "Hello";
    test[1].str = "World";

    Console.WriteLine("Count : " + test.Count);
}


class MyClass
{
    public string str;
}

Upvotes: 0

Views: 1655

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

First your code should be like

MyClass[] test = new MyClass()[2];

second if you want to know how many instances of your class has been generated. create a

public static int Count;

and increment its property in the constructor of your class like

public MyClass()
{
    Count++;
}

If you want to know the number of instances then just write

MessageBox.Show(Myclass.Count.ToString());

Upvotes: 0

JWL_
JWL_

Reputation: 829

Your custom class is not aware of the fact that it's in an array. Therefore you can not get a count of the number of objects in your array since only Main() knows how many object the array contains.

Upvotes: 1

KingCronus
KingCronus

Reputation: 4519

You have made an array, so it should already have a test.Length property.

Upvotes: 2

Related Questions