The book of inspiration

April 22, 2009

Named Integers in C# aka Typedef

Filed under: life — Tags: , , , — zproxy @ 7:35 am

The other day I was wondering if there was anything like a named integer in C#. Today it struck me. We could define a new enum to function as a good old typedef. An enum can inherit from any integer. See the recent discussion here. While reading this article stateing java enums can define methods for enums I thought C# could use extension methods for that. Enums can reference a value not explicitly defined by the enum itself. In this case I did not define any values for that enum.

Here is a prototype for creating a named integer and defineing a method for it:

    8 public enum NamedInteger
    9 {
   10
   11 }
   12
   13 public static class NamedIntegerExtensions
   14 {
   15   public static void Method1(this NamedInteger e, string text)
   16   {
   17     Console.WriteLine("Method1: " + (int)e + " - " + text);
   18   }
   19 }
   20
   21 class Program
   22 {
   23   static void Main(string[] args)
   24   {
   25     var x = default(NamedInteger);
   26
   27     x.Method1("hello world");
   28   }
   29 }
About these ads

The Shocking Blue Green Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 74 other followers

%d bloggers like this: