Friday, July 08, 2005

Custom Classes are NOT Value Types...

This is for all the confusion that is often caused due to a commonly made mistake all of us make at some point of time - Classes are NOT Value types! In other words when you assign an object of a class to a variable you are assigning a reference and not a 'copy' of the value! So, basically a change in either one of the objects now reflects in both. Followin Code snippet illustrates:

Employee rajivpopat = new Employee();
rajivpopat.EmployeeName = "rajivpopat";
rajivpopat.EmployeeDOB = System.Convert.ToDateTime("11/24/1981");
rajivpopat.AdditionalContactDetails = "AdditionalDetails";

Employee chetanpopat = rajivpopat;
chetanpopat.EmployeeName = "chetanpopat";
MessageBox.Show(rajivpopat.EmployeeName);
This shows and output "chetanpopat" - because change of chetanpopat.EmployeeName = "rajivpopat" has changed the vallue that rajivpopat.EmployeeName was referencing!!!

Structs however, work with a different concept and are Value Types! The Same code would return "rajivpopat" if Employee was defined as a struct! You'll not be able to initialize values of fields in struct and they will all be initialized by default value!!!

0 Comments:

Post a Comment

<< Home