static void StructVSClass() { //Note!!! - Both class and struct use the 'new' keyword TheClass testClass = new TheClass(); TheStruct testStruct = new TheStruct(); /* Initialize both Class and Struct to 'Not Changed' */ testClass.willIChange = "Not Changed"; testStruct.willIChange = "Not Changed"; /* * Made extension methods * Extension methods require class to be static and parameter to have 'this' * Set both Class and Struct to 'Not Changed' * * */ testClass.ClassTaker(); //Struct is a value type and may create a new instance but will not change. testStruct.StructTaker(); // Could also call it this way, however extension methods is preferrred // ClassTaker(testClass); // StructTaker(testStruct); // // Displays Class field "changed" // Struct field "not changed" // Console.WriteLine("Class field = {0}", testClass.willIChange); Console.WriteLine("Struct field = {0}", testStruct.willIChange); }
static void StructTaker(this TheStruct s) { s.willIChange = "Changed"; }