Can please someone enlight me, I don't understand this:
It is possible in C# to "reach" inside a boxed value type through an
interface like in the following code:
interface IPerson
{
string Name { get; set;}
}
public struct Person : IPerson
{
public Person(string name)
{
m_Name = name;
}
public string Name
{
get { return m_Name; }
set { m_Name = value;}
}
public override string ToString()
{
return m_Name;
}
private string m_Name;
};
class Program
{
static void Main(string[] args)
{
Person p = new Person("Old Name");
ArrayList attendees = new ArrayList();
attendees.Add(p);
((IPerson)attendees[0]).Name = "New Name";
Console.WriteLine(attendees[0].ToString());
}
}
This will write "New Name" on the console.
But when I replace ArrayList with the generic List it doesn't work
anymore:
Person p = new Person("Old Name");
List<Person> genericAttendees = new List<Person>();
genericAttendees.Add(p);
((IPerson)genericAttendees[0]).Name = "New Name";
Console.WriteLine(genericAttendees[0].ToString());
This will print "Old Name". Why?
Regards,
Gunter
P.S.: I know, value types should be immutable. This is another example
why :)