locked
typedef-equivalent for shared tentative types? RRS feed

  • Question

  • (This topic has been touched on here and here.)

    Use case: Developers are working concurrently on a system where some details of the implementation remain unsettled.  One of the details is whether a particular Id will be a string or an integer.

    We can write:

    using PlantId = Int32;
    using AnimalId = String;
    class Plants : List<PlantId> {}
    class Animals : List<AnimalId> {}

    void useList(Plants p)
    {
       PlantId firstPlant = p[0];
       TextBox1.Text = firstPlant.ToString();
    }

    If we decide to use Strings for PlantId, we just change the first line, and everything compiles.  The problem is, using is file scope, so the using clause needs to be repeated everywhere we want this flexibility to work.

    Is there any other syntax that will enable the developers who can make progress without knowing the actual type of the objects they're manipulating?  Is there a way to #include a block of using statements in multiple files?  Is there an unsealed version of Int32 from which we could derive?

    Wednesday, May 24, 2006 1:26 PM

All replies

  • Hi,

    What if you created a class 'PlantId' and provided implicit and explicit cast operator overrides to the type you want to use (e.g. int or string) as well as ToString() overrides. Store the underlying value in a private field.

    When the underlying type changes, you will of course get compiler errors everywhere in your code where you cast to/from the previous type if you remove the casts from the underlying class.

    When you decide the final type of the object, refactor it into this type and if you provided all the correct overrides when you created the class, you should be fine.

    Stephane

    ps -  you could probably do this with a struct instead of a class as well, but that would essentially be the same if you plan to replace the type later anyway.

    Wednesday, May 24, 2006 2:03 PM




  • What if you created a class 'PlantId' and provided implicit and explicit cast operator overrides to the type you want to use (e.g. int or string) as well as ToString() overrides. Store the underlying value in a private field.

    When the underlying type changes, you will of course get compiler errors everywhere in your code where you cast to/from the previous type if you remove the casts from the underlying class.

    When you decide the final type of the object, refactor it into this type and if you provided all the correct overrides when you created the class, you should be fine.






    That's a great idea (you should make that class a child of IComparable), but C# should implement typedefs, they're so useful in generic programming.

    Thursday, December 10, 2009 11:47 PM