class Person
{
public string
FirstName { get; set; }
public string LastName
{ get; set; }
public override string
ToString() { return $"{FirstName} {LastName}"; }
}
class People
{
Person[] _ppl;
public People(params Person[] ppl)
{
_ppl = ppl;
}
public Person this[int Index]
{
get { return
_ppl[Index]; }
set { _ppl[Index] = value; }
}
}
let's take a look at our implementation
class Program
{
static void Main(string[] args)
{
var p1 = new Person { FirstName = "Pawel", LastName = "Ciucias" };
var p2 = new Person { FirstName = "Tomek", LastName = "Ciucias" };
var p3 = new Person { FirstName = "Jakub", LastName = "Tywoniuk" };
var p4 = new Person { FirstName = "Magda", LastName = "Tywoniuk" };
//becasue of
the params key word
var ppl = new People(p1, p2, p3, p4);
//because of
the indexer
Console.WriteLine(ppl[3]);
}
}
now if we wanted to use a for loop over our People collection, we wouldn't be able to since we don't expose a length method, we could try using a while loop, but eventually we'd get a index out of range exception; instead let's just implement a length property.
class People
{
Person[] _ppl;
public People(params Person[] ppl)
{
_ppl = ppl;
}
public Person this[int Index]
{
get { return
_ppl[Index]; }
set { _ppl[Index] = value; }
}
public int Length {
get { return _ppl == null ? 0 : _ppl.Length; }
}
}
class Program
{
static void Main(string[] args)
{
var p1 = new Person { FirstName = "Pawel", LastName = "Ciucias" };
var p2 = new Person { FirstName = "Tomek", LastName = "Ciucias" };
var p3 = new Person { FirstName = "Jakub", LastName = "Tywoniuk" };
var p4 = new Person { FirstName = "Magda", LastName = "Tywoniuk" };
//becasue of
the params key word
var ppl = new People(p1, p2, p3, p4);
for(var i = 0; i
< ppl.Length; i++)
Console.WriteLine(ppl[i].ToString());
}
}