T
Tony Johansson
Hello!
The question is about this assignment statement Person pp = arrList[0];
I know that to correct the error I have to write Person pp =
(Person)arrList[0];
But my question is the following.
This statement give compile error. I have always thought that the compiler
doesn't see these kind of error which
therefore only give run time error of type InvalidCastException.
I'm I wrong in some way. I have even read this in some books that the
compiler only see the type when
taken from the collection and assigning to a new object type.
class Program
{
ArrayList arrList = new ArrayList();
public Program()
{
arrList.Add(new Person("123456-1234", "Nisse", 14));
arrList.Add(new Person("987654-4321", "Pelle", 15));
arrList.Add(new Person("563423-7612", "Stina", 35));
Person pp = arrList[0];
}
static void Main(string[] args)
{
Program prog = new Program();
}
}
class Person
{
private string pers_nr;
private string name;
private int age;
public Person(string pers_nr, string name, int age)
{
this.pers_nr = pers_nr;
this.name = name;
this.age = age;
}
public string Pers_nr
{
get { return pers_nr; }
set { pers_nr = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public override string ToString()
{
return string.Format("Pers_nr = {0} Name = {1} Age = {2}",
Pers_nr, Name, Age);
}
}
//Tony
The question is about this assignment statement Person pp = arrList[0];
I know that to correct the error I have to write Person pp =
(Person)arrList[0];
But my question is the following.
This statement give compile error. I have always thought that the compiler
doesn't see these kind of error which
therefore only give run time error of type InvalidCastException.
I'm I wrong in some way. I have even read this in some books that the
compiler only see the type when
taken from the collection and assigning to a new object type.
class Program
{
ArrayList arrList = new ArrayList();
public Program()
{
arrList.Add(new Person("123456-1234", "Nisse", 14));
arrList.Add(new Person("987654-4321", "Pelle", 15));
arrList.Add(new Person("563423-7612", "Stina", 35));
Person pp = arrList[0];
}
static void Main(string[] args)
{
Program prog = new Program();
}
}
class Person
{
private string pers_nr;
private string name;
private int age;
public Person(string pers_nr, string name, int age)
{
this.pers_nr = pers_nr;
this.name = name;
this.age = age;
}
public string Pers_nr
{
get { return pers_nr; }
set { pers_nr = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public override string ToString()
{
return string.Format("Pers_nr = {0} Name = {1} Age = {2}",
Pers_nr, Name, Age);
}
}
//Tony