code_junkie

How do you give a C# Auto-Property a default value?

Nov 10th, 2011
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. class Person
  2. {
  3. public Person()
  4. {
  5. Name = "Default Name";
  6. }
  7. public string Name { get; set; }
  8. }
  9.  
  10. private string name = "Default Name";
  11. public string Name
  12. {
  13. get
  14. {
  15. return name;
  16. }
  17. set
  18. {
  19. name = value;
  20. }
  21. }
  22.  
  23. class Person
  24. {
  25. public Person()
  26. {
  27. //do anything before variable assignment
  28.  
  29. //assign initial values
  30. Name = "Default Name";
  31.  
  32. //do anything after variable assignment
  33. }
  34. public string Name { get; set; }
  35. }
  36.  
  37. class Person
  38. {
  39. private string _name;
  40. public string Name
  41. {
  42. get
  43. {
  44. return string.IsNullOrEmpty(_name) ? "Default Name" : _name;
  45. }
  46.  
  47. set { _name = value; }
  48. }
  49. }
  50.  
  51. private bool bShowGroup ;
  52. [Description("Show the group table"), Category("Sea"),DefaultValue(true)]
  53. public bool ShowGroup
  54. {
  55. get { return bShowGroup; }
  56. set { bShowGroup = value; }
  57. }
  58.  
  59. public class DefaultValuesTest
  60. {
  61. public DefaultValuesTest()
  62. {
  63. foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
  64. {
  65. DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
  66.  
  67. if (myAttribute != null)
  68. {
  69. property.SetValue(this, myAttribute.Value);
  70. }
  71. }
  72. }
  73.  
  74. public void DoTest()
  75. {
  76. var db = DefaultValueBool;
  77. var ds = DefaultValueString;
  78. var di = DefaultValueInt;
  79. }
  80.  
  81.  
  82. [System.ComponentModel.DefaultValue(true)]
  83. public bool DefaultValueBool { get; set; }
  84.  
  85. [System.ComponentModel.DefaultValue("Good")]
  86. public string DefaultValueString { get; set; }
  87.  
  88. [System.ComponentModel.DefaultValue(27)]
  89. public int DefaultValueInt { get; set; }
  90. }
  91.  
  92. class Person
  93. {
  94. /// Gets/sets a value indicating whether auto
  95. /// save of review layer is enabled or not
  96. [ System.ComponentModel.DefaultValue(true)]
  97. public bool AutoSaveReviewLayer { get; set; }
  98. }
  99.  
  100. class Person
  101. {
  102. private string _name;
  103.  
  104. [DefaultValue(true)]
  105. public string Name
  106. {
  107. get { return _name; }
  108. set { _name = value; }
  109. }
  110. }
Add Comment
Please, Sign In to add comment