Advertisement
Tishy

C# Reference and Value-types

Sep 7th, 2019
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. /*Reference: Passing the original object that can be changed
  2. Value: Passing a value is like copying it, the initial value stays untouched
  3.  
  4. Related keywords:
  5. ref
  6. - used to pass a reference
  7. - May be modified by the called method
  8. out
  9. - used to pass a reference
  10. - Must be modified by the called method
  11. in
  12. - used to pass a reference
  13. - Can't be modified by the called method
  14.  
  15. */
  16.  
  17.  
  18.  
  19.     class Reference //classes are by default reference types
  20.     {
  21.         public int property { get; set; }
  22.     }
  23.  
  24.     struct Value //structs are by default value types
  25.     {
  26.         public int property { get; set; }
  27.     }
  28.  
  29.     class App
  30.     {
  31.         public static void Main()
  32.         {
  33.             int apples = 8;
  34.             int bananas = 15;
  35.  
  36.             DoStuff(apples, ref bananas);
  37.             Console.WriteLine($"apples: {apples}\nbananas: {bananas}\n");
  38.             //Output: apples: 8, bananas: 6969         
  39.  
  40.             Reference myClass = new Reference();
  41.             Value myStruct = new Value();
  42.  
  43.             myClass.property = 99;
  44.             myStruct.property = 77;
  45.  
  46.             DoOtherStuff(myClass, myStruct);
  47.             Console.WriteLine($"Class: {myClass.property}\nStruct: {myStruct.property}");
  48.             //Output: Class: 420, Struct: 77
  49.         }
  50.  
  51.         public static void DoStuff(int value, ref int reference)
  52.         {
  53.             value = 69;
  54.             reference = 6969;
  55.         }
  56.  
  57.         public static void DoOtherStuff(Reference aClass, Value aStruct)
  58.         {
  59.             aClass.property = 420;
  60.             aStruct.property = 1337;
  61.         }
  62.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement