Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 812
sorush-r Avatar asked Mar 23 '26 04:03

sorush-r


1 Answers

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.

like image 54
Anton Gogolev Avatar answered Mar 24 '26 18:03

Anton Gogolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!