Home > Net >  Array of objects
Array of objects

Time:09-29

I am new to c# and just practicing with object arrays. tried to display the elements of the array using loop but this code didn't display anything. Please help

using System;
using System.Text;
   
namespace pra
{
    class program
    {
        public static void Main(string[] args)
        {
      
        person[] person1 = new person[2];

        person1[0] = new person("Mike");
        person1[1] = new person("John");

        for (int i =0; i < person1.Length; i  )
        {
            Console.WriteLine("{0}",person1[i].Name);
        }
    }


    
}
class person
{
    string name;
    public string Name { get; set; }

    public person(string name)
    {
        this.name = name;
    }
}

}

CodePudding user response:

You're setting a value to the name field (which is never read), then reading from the Name property (which was never set).

You don't need (or want) both of them here. Remove the field and just use the property:

class person
{
    public string Name { get; set; }

    public person(string name)
    {
        this.Name = name;
    }
}

CodePudding user response:

The way to make it work is to change your Person class

class person
{
    string name;
    public string Name { get=>name; set=>name=value; }
    public person(string name)
    {
        this.name = name;
    }
}

CodePudding user response:

You don't need the field name and an auto property Name at the same time. If you store the value in name it, won't be accessible by the property Name, unless you write a getter and a setter to do so. But with C# you can skip all that and just use an auto property with a hidden backing field.

class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        this.Name = name;
    }
    public override string ToString()
    {
        return Name;
    }
}

You can also simplify the conversion between Person and string by overriding the ToString() method. See example usage below:

class Program
{
    public static void Main(string[] args)
    {
      
        Person[] array= new Person[2];

        array[0] = new Person("Mike");
        array[1] = new Person("John");

        for (int i =0; i < array.Length; i  )
        {
            Console.WriteLine(array[i]);
        }
    }
}

You will notice that the WriteLine() statement will display each person's Nameproperty because that is what theToString()` method instructs it to do. Control of what and how it is displayed is in the class and not with the program.

PS. Also, note that class names and types should be capitalized in order to distinguish them from fields and variables. Properties also should be capitalized.

  • Related