473,394 Members | 1,755 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Modyfing value types through an interface doesn't work with generics (Brain Puzzle?)

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 :)

Mar 24 '06 #1
2 1280
I think I can answer the puzzle myself.

Casting a value type to an interface always leads to boxing
(http://blogs.msdn.com/abhinaba/archi...5/477238.aspx).

This is the case with the generic list, so a copy gets modified.

Casting the boxed object back to the original value type doesn't work
and gives you an Compiler Error CS0445 ("Cannot modify the result of an
unboxing conversion").

But you can cast a boxed object (back) to an interface. This generates
a castclass opcode in IL which means no boxing/unboxing takes place. So
this time the original value gets modified.

When a value type is converted to an object an unnamed reference type
is created. All methods (also from interfaces) accessing the value type
are passed through this box.

What really puzzles it that when we use the generic list, boxing gets
in the way whereas in the object version its does not!

Really confusing. Value types should REALLY be immutable. And don't use
interfaces for value types if they are not.

Regards,
Gunter

Mar 24 '06 #2
BTW,

The code analysis feature of Visual Studio 2005 (former FxCop) doesn't
give one hint at problem. I think it should.

Regards,
Gunter

Mar 24 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: sneill | last post by:
How is it possible to take the value of a variable (in this case, MODE_CREATE, MODE_UPDATE, etc) and use that as an object property name? In the following example I want 'oIcon' object to have...
24
by: | last post by:
Hi, I need to read a big CSV file, where different fields should be converted to different types, such as int, double, datetime, SqlMoney, etc. I have an array, which describes the fields and...
4
by: Dietmar Kuehl | last post by:
Hi, after reading the documentation on C# generics from several sources, I'm still unclear whether it is possible to infer associated types from a type argument. For example, if I have an...
7
by: Leicester B. Ford Jr. | last post by:
I have this class: public class ItemType .... public class ProductType<T> where T: ItemType .... Now I want to add an IDisposable interface to ProductType...
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
7
by: stephan querengaesser | last post by:
hi ng, i try to invoke a webservice-method with an filter-object, that contains value types. if i donīt want to filter the return value of the method, i have to pass a new instance of the...
2
by: Herby | last post by:
I need to define my own types and arrays of these types. These types are for the most part extensions of the built in types and need to provide all the basic operations of arithmetic and...
12
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
14
by: KK | last post by:
Dear All I have a small problem with using as operator on value type array. Here is an example what I am trying to do. using System; using System.Collections.Generic; using System.Text;
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.