473,569 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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,1 2,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 1299

"Sahil Malik [MVP]" <co************ *****@nospam.co m> wrote in message
news:%2******** ********@TK2MSF TNGP12.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,1 2,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<MyValueTyp e> aList = ... ;
aList[i].MethodThatModi fiesValue();

will modify a temporary copy of the value, not the value in the
List<MyValueTyp e>. The value in the List<MyValueTyp e> 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*******@cana da.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.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<MyValueTyp e> aList = ... ;
aList[i].MethodThatModi fiesValue();

will modify a temporary copy of the value, not the value in the
List<MyValueTyp e>. The value in the List<MyValueTyp e> 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,1 2,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
10067
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 since DBNull cannot be converted to int. I wrote the following method that looks up the column's data type and if it is a ValueType, returns the...
0
2497
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 since DBNull cannot be converted to int. I wrote the following method that looks up the column's data type and if it is a ValueType, returns the...
6
2133
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 signature, it is said to be covariant. Because the method's return type is more specific than the delegate signature's return type, it can be implicitly...
2
3833
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 since DBNull cannot be converted to int. I wrote the following method that looks up the column's data type and if it is a ValueType, returns the...
0
7922
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7964
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5218
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2111
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1209
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.