// using Class vs Struct static void ClassTaker(TheClass c) { c.willIChange = "Changed"; }
// Normally, all the objects are passed by reference as parameter to the method. // On the other hand most of the primitive data types such as integer, double, Boolean etc. are passed by value. public static void ParametersTest() { Console.WriteLine("Hello World!"); int y = 5; // initialize y to 5 int z; // declares z, but does not initialize it // display original values of y and z Console.WriteLine($"Original value of y: {y}"); Console.WriteLine("Original value of z: uninitialized\n"); // pass y and z by reference SquareRef(ref y); // must use keyword ref SquareOut(out z); // must use keyword out // display values of y and z after they're modified by // methods SquareRef and SquareOut, respectively Console.WriteLine($"Value of y after SquareRef: {y}"); Console.WriteLine($"Value of z after SquareOut: {z}\n"); // pass y and z by value Square(y); // display values of y and z after they're passed to method Square // to demonstrate that arguments passed by value are not modified Console.WriteLine($"Value of y after Square: {y}\n"); // pass y and z by value Square(z); Console.WriteLine($"Value of z after Square: {z}\n"); Person p1 = new Person { name = "John", age = 20 }; Console.WriteLine($"before Person: name: {p1.name} age: {p1.age}\n"); ChangeAge(p1); Console.WriteLine($"after ChangeAge: name: {p1.name} age: {p1.age}\n"); ChangeAgeRef(ref p1); Console.WriteLine($"after ChangeAgeRef: name: {p1.name} age: {p1.age}\n"); // using Class vs Struct Console.WriteLine("using Class vs Struct:"); TheClass testClass = new TheClass(); TheStruct testStruct = new TheStruct(); testClass.willIChange = "Not Changed"; testStruct.willIChange = "Not Changed"; ClassTaker(testClass); StructTaker(testStruct); Console.WriteLine("Class field = {0}", testClass.willIChange); Console.WriteLine("Struct field = {0}", testStruct.willIChange); // using out to return multiple values int argNumber; string argMessage, argDefault; Method(out argNumber, out argMessage, out argDefault); Console.WriteLine($"argNumber = {argNumber}, argMessage = {argMessage}, argDefault = {argDefault == null}"); Console.ReadLine(); }