Guest User

Untitled

a guest
Jan 23rd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. using System;
  2.  
  3. public class Program
  4. {
  5. public static void Main()
  6. {
  7. var currentCount = Person.GetCounter;
  8. Console.WriteLine(string.Format("Current Person Count: {0}", currentCount));
  9.  
  10. var matt = new Person("matt", "lizzy", "pizzy");
  11. var nick = new Person("nick", "yizzy", "fizzy");
  12.  
  13. Console.WriteLine(string.Format("Nick: {0} {1} {2}", nick.FirstName, nick.MiddleName, nick.LastName));
  14. Console.WriteLine(string.Format("Matt: {0} {1} {2}", matt.FirstName, matt.MiddleName, matt.LastName));
  15.  
  16. var newCount = Person.GetCounter;
  17. Console.WriteLine(string.Format("New Person Count: {0}", newCount));
  18. }
  19.  
  20.  
  21. public class Person
  22. {
  23. // this is a private field - only code in this class can access it
  24. private static int _counter;
  25. // public getter for our counter
  26. public static int GetCounter { get { return _counter; } }
  27.  
  28. // private fields
  29. private string _firstName;
  30. private string _lastName;
  31.  
  32. // public getter/setter that let us manipulate private fields
  33. public string FirstName
  34. {
  35. get { return _firstName; }
  36. set { _firstName = value; }
  37. }
  38.  
  39. public string LastName
  40. {
  41. get { return _lastName; }
  42. set { _lastName = value; }
  43. }
  44.  
  45. // or you could just expose props publicly, and the data behind them, which isnt recommended
  46. public string MiddleName { get; set; }
  47.  
  48. // class constructor - you can tell because the 'method' is named the same as the class
  49. public Person(string fn, string ln, string mn)
  50. {
  51. FirstName = fn;
  52. LastName = ln;
  53. MiddleName = mn;
  54. // incriment counter
  55. _counter++;
  56. }
  57. }
  58. }
  59.  
  60. /** OUTPUT:
  61. Current Person Count: 0
  62. Nick: nick fizzy yizzy
  63. Matt: matt pizzy lizzy
  64. New Person Count: 2
  65. */
Add Comment
Please, Sign In to add comment