开发者

Why System.String beahaves like a value type? (How to write value type classes like string?)

开发者 https://www.devze.com 2022-12-31 07:33 出处:网络
I want to write a \'Date\' class that behaves like a Value Type. for example, Instead of writing a Clone method for setting properties safely, make the Date class to pass by value:

I want to write a 'Date' class that behaves like a Value Type. for example, Instead of writing a Clone method for setting properties safely, make the Date class to pass by value:

public Date Birthday
        {
 开发者_开发问答           get { return this.birthday; }
            set 
            { 
               this.birthday = value.Clone(); 
            } //I want to write this.birthday = value; 
              //without changing external value when this.Birthday changes
        }

I know this is possible because System.String is a class and behaves like a value. for example:

String s1 = "Hello";
String s2 = "Hi";
s1 = s2;
s2="Hello";
Console.WriteLine(s1);  //Prints 'Hi'

First I thought writers of this class override '=' operator, but now I know that the '=' operator can not be overridden. so how they write String class?

Edit: I just want to make my Date class to pass it's instances by value, like as String.


First, your string-based example does not illustrate your question.

The thing with DateTime and String is that they are immutable: once an instance is created, it cannot be changed in any way. For example, you cannot add 2 minutes to a DateTime instance by just saying date.Minutes += 2: you'll have to invoke date.AddMinutes(2), which will yield a totally new instance.

To make objects read-only, just follow the same pattern.


public class Date{ ...code...} would be a reference type...not what you want.

public struct Date { ...code...} would be a value type...probably what you want.

The string class is, as it is a class, a reference type...and is immutable..how being immutable effects the behavior of string objects can be confusing at the start.

Given string s1 = "Fish"; s1 is a reference that points to "Fish"...It is the "Fish" bit can never be changed....what s1 points to can be changed. If you then assign s1 = "Tuna"; "Fish" still exists but is no longer referenced and will be GC'd.

In your example after: s1=s2 s1,s2 now reference the same string "Hi"...there is only one "Hi".

I hope I have not gone way below your level.


It's not the '=' operator, it's the fact that when you say

stringThing = "thing";

you're creating a new string, not changing the current string to something else.

0

精彩评论

暂无评论...
验证码 换一张
取 消