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.
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 assigns1 = "Tuna";“Fish” still exists but is no longer referenced and will be GC’d.In your example after:
s1=s2s1,s2 now reference the same string “Hi”…there is only one “Hi”.I hope I have not gone way below your level.