473,395 Members | 2,796 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,395 software developers and data experts.

Weird Valuetype behavior

Okay so lets say I have a valuetype - lets say DateTime.

Look at this code .

List<DateTime> dt = new List<DateTime>() ;
dt.Add(new dateTime(1999,12,1))
dt[0].AddDays(1) ;
<--- This statement won't actually change the date time stored in the
List<T> dt.

The best I can determine is that soon as a method is called on any date time
stored in "dt", it creates a new instance of DateTime, and leaves the
original inside dt untouched. Similar behavior for non generic collections.

Can anyone explain the reasoning?

- Sahil Malik [MVP]
http://codebetter.com/blogs/sahil.malik/


Nov 17 '05 #1
4 1286

"Sahil Malik [MVP]" <co*****************@nospam.com> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
Okay so lets say I have a valuetype - lets say DateTime.

Look at this code .

List<DateTime> dt = new List<DateTime>() ;
dt.Add(new dateTime(1999,12,1))
dt[0].AddDays(1) ;
<--- This statement won't actually change the date time stored in the
List<T> dt.

The best I can determine is that soon as a method is called on any date
time
stored in "dt", it creates a new instance of DateTime, and leaves the
original inside dt untouched. Similar behavior for non generic
collections.

Can anyone explain the reasoning?


This has nothing to do with the collections
AddDays() (and similar methods)
do not modify the original DateTime

you need to capture the return value
DateTime now = DateTime.Now;
DateTime datetime = now.AddDays(1);

Bill
Nov 17 '05 #2
As Bill Butler pointed out, AddDays doesn't modify the original
DateTime structure.

However, even if it did, I don't believe that it would change the
DateTime stored in the List<DateTime>. Here is why.

Remember two things: first, a reference like dt[0], where dt is a
List<DateTime>, is really just a method call. Somewhere in the
definition for List<T> is a method declaration that unwinds to look
something like this:

public DateTime this[index i]
{
DateTime dt = ... ;
return dt;
}

Second, remember that value types, like DateTime, are always copied.

So, what will happen is that some code will run that will find the
correct DateTime value within the list. That value will then be _copied
on the stack_ as the return value from the this[] indexer method. Any
method or property that then modifies that DateTime will modify the
temporary value on the stack, the value that was returned from the
indexer.

Therefore, saying

List<MyValueType> aList = ... ;
aList[i].MethodThatModifiesValue();

will modify a temporary copy of the value, not the value in the
List<MyValueType>. The value in the List<MyValueType> will remain
unchanged.

This doesn't even have to do with boxing and unboxing... it has to do
with how value types are returned from method calls.

All of which demonstrates once again why creating mutable value types
is just asking for trouble.... :-)

Nov 17 '05 #3
Thanks Bruce.

Instead of
public DateTime this[index i]
{
DateTime dt = ... ;
return dt;
}
Why didn't theyhave something like this -
public DateTime this[index i]
{
return innercollection[i];
}
Would that help the situation any?

- Sahil Malik [MVP]
http://codebetter.com/blogs/sahil.malik/


"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com... As Bill Butler pointed out, AddDays doesn't modify the original
DateTime structure.

However, even if it did, I don't believe that it would change the
DateTime stored in the List<DateTime>. Here is why.

Remember two things: first, a reference like dt[0], where dt is a
List<DateTime>, is really just a method call. Somewhere in the
definition for List<T> is a method declaration that unwinds to look
something like this:

public DateTime this[index i]
{
DateTime dt = ... ;
return dt;
}

Second, remember that value types, like DateTime, are always copied.

So, what will happen is that some code will run that will find the
correct DateTime value within the list. That value will then be _copied
on the stack_ as the return value from the this[] indexer method. Any
method or property that then modifies that DateTime will modify the
temporary value on the stack, the value that was returned from the
indexer.

Therefore, saying

List<MyValueType> aList = ... ;
aList[i].MethodThatModifiesValue();

will modify a temporary copy of the value, not the value in the
List<MyValueType>. The value in the List<MyValueType> will remain
unchanged.

This doesn't even have to do with boxing and unboxing... it has to do
with how value types are returned from method calls.

All of which demonstrates once again why creating mutable value types
is just asking for trouble.... :-)

Nov 17 '05 #4
Nope. No joy. It's still a method with a return value, which still
means that the value type (in this case DateTime) gets copied onto the
stack, which still means that what you get back is a copy, not a
reference to the item in the array.

You have to think of arrays of complex value types like DateTime in the
same way that you think of arrays of integers. You can put a new
integer at a particular place in the array, but you can't "modify" the
integer that's already in the array... that doesn't make any sense.

Which, again, is why mutable value types are so weird. Yes, C# lets you
create them, but I consider that very, very fragile code, and would ask
the person why they're doing it.

No, no matter how you slice it, you have to say:

List<DateTime> dt = new List<DateTime>() ;
dt.Add(new dateTime(1999,12,1))
dt[0] = dt[0].AddDays(1) ;

in other words, on that last line you have to read the value from
dt[0], call AddDays to produce a new value from it, and replace the
contents of dt[0] with that new value, just the way you would with an
integer:

intList[0] = intList[0] + 1;

(By the way, I haven't tried it, but if I'm right, the following code
should have the same effect that you described for DateTimes:

intList[0]++;

The value of the integer at intList[0] should not change because the
postincrement operator is incrementing a copy on the stack, not the int
stored in the List.)

Nov 17 '05 #5

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

Similar topics

4
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception...
0
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception...
6
by: Aryeh Holzer | last post by:
Let me start with a quote from the C# Programmers Reference (where I learned the cool word "covariance"): "When a delegate method has a return type that is more derived than the delegate...
2
by: Brian Brane | last post by:
I have properties that wrap DataRow columns as in: public int aNumber { get{ return m_DataRow; } set{ m_DataRow = value; } } If the column happens to contain DBNull, I get a cast exception...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.