Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time tree structure

I want to retrieve values from a tree stored in another system. For example:

GetValue("Vehicle.Car.Ford.Focus.Engine.Oil.Color")

To avoid typing errors and invalid keys, I want to check the name at compile time by creating an object or class with the tree structure in it:

GetValue(Vehicle.Car.Ford.Focus.Engine.Oil.Color)

Is there an easy way to do this in C# without creating classes for each tree node? Can I use anonymous classes or subclasses? Should I create the code automatically?

like image 980
Sjoerd Avatar asked Jun 09 '11 07:06

Sjoerd


1 Answers

If you want compile-time checking, you need to define your structure using compile-time constructs in some way. You could use T4 text template to automatically generate code from the tree structure.

Possible ways I can think of:

Nested static classes

public static class Vehicle
{
    public static class Car
    {
        public static class Ford
        {
            public static class Focus
            {
                public static class Engine
                {
                    public static class Oil
                    {
                        public static readonly string Color =
                            "Vehicle.Car.Ford.Focus.Engine.Oil.Color";
                    }
                }
            }
        }
    }
}

Namespaces and static classes

namespace Vehicle.Car.Ford.Focus.Engine
{
    public static class Oil
    {
         public static readonly string Color =
             "Vehicle.Car.Ford.Focus.Engine.Oil.Color";
    }
}

(Note that you can't have both a class Ford in namespace Vehicle.Car and classes in a namespace Vehicle.Car.Ford.)

like image 121
dtb Avatar answered Sep 30 '22 07:09

dtb