Implement indexer to access array type member fields - CSharp Custom Type

CSharp examples for Custom Type:Indexer

Description

Implement indexer to access array type member fields

Demo Code

using static System.Console;
using System;// ww w .ja v a  2  s  .  com
using System.Collections.Generic;
class Program
{
   static void Main(string[] args)
   {
      var sam = new Person
      {
         Name = "Sam",
         DateOfBirth = new DateTime(2020, 1, 27)
      };
      sam.Children.Add(new Person { Name = "White" });
      sam.Children.Add(new Person { Name = "Her" });
      WriteLine($"Sam's first child is {sam.Children[0].Name}");
      WriteLine($"Sam's second child is {sam.Children[1].Name}");
      WriteLine($"Sam's first child is {sam[0].Name}");
      WriteLine($"Sam's second child is {sam[1].Name}");
   }
}
public class Person : object
{
   public string Name;
   public DateTime DateOfBirth;
   public List<Person> Children = new List<Person>();
   public readonly DateTime Instantiated;
   public const string Species = "Programmer";
   public readonly string HomePlanet = "Earth";
   public Person()
   {
      Name = "Unknown";
      Instantiated = DateTime.Now;
   }
   public string FavoriteIceCream { get; set; } // auto-syntax
   public Person this[int index]
   {
      get
      {
         return Children[index];
      }
      set
      {
         Children[index] = value;
      }
   }
}

Result


Related Tutorials