Tuesday, November 15, 2011

Example: C# dynamic 'Enum' like solution.

Example usage:


Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace GuiLib.TeraRegion
  5. {
  6.     public class TeraRegionModel
  7.     {
  8.  
  9.         /// <summary>
  10.         /// Dynamic enum of RegionTypes.
  11.         /// <remarks>* This is a [Flags] and normal mixed enum!
  12.         /// * 0 is reserved! it's not used!
  13.         /// * 1 is reserved! it's void.
  14.         /// Find it's max and assigne it's next value like this:
  15.         ///     var next_enum_val = RegionTypes.Values.Max<ulong>();
  16.         ///     RegionTypes.Add("new_item", next_enum_val*2);
  17.         /// </remarks>
  18.         /// </summary>
  19.         public static Dictionary<string, ulong> RegionTypes = new Dictionary<string, ulong>()
  20.         {
  21.             {"void", 1}
  22.         };
  23.  
  24.  
  25.         #region RegionType
  26.  
  27.         /// <summary>
  28.         /// Occurs when RegionType changes.
  29.         /// </summary>
  30.         public event EventHandler RegionTypeChanged;
  31.  
  32.         /// <summary>
  33.         /// Raises the <see cref="E:RegionTypeChanged"/> event.
  34.         /// </summary>
  35.         /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
  36.         protected virtual void OnRegionTypeChanged(EventArgs e)
  37.         {
  38.             if (RegionTypeChanged != null)
  39.                 RegionTypeChanged(this, e);
  40.         }
  41.  
  42.         private ulong _RegionType = 1;
  43.  
  44.  
  45.         /// <summary>
  46.         /// Gets or sets the type of the region.
  47.         /// </summary>
  48.         /// <value>
  49.         /// The type of the region.
  50.         /// </value>
  51.         public ulong RegionType
  52.         {
  53.             get
  54.             {
  55.                 return _RegionType;
  56.             }
  57.  
  58.             set
  59.             {
  60.                 if (_RegionType != value)
  61.                 {
  62.                     _RegionType = value;
  63.  
  64.                     OnRegionTypeChanged(new EventArgs());
  65.                 }
  66.             }
  67.         }
  68.         #endregion
  69.  
  70.     }
  71. }

1 comment:

  1. Original post:
    http://shloemi.blogspot.com/2011/11/tip-c-dynamic-enum-like-solution.html

    ReplyDelete