Question

I have a problem with convertion types. My mainForm keeps variable in integer type. Also my form has propertyGrid where I realized property for field (like combobox) with Image & Text. And now I don't understand well how can I convert one type into another. First I need to convert data from int to myProp and then vice versa. Here setup propertyGrid:

    public dashPatternList DashPattern
    {
        get { return dashPattern; }
        set { dashPattern = value; }
    }

Here I tried to realize my problem with additional methods:

    private dashPatternList dashIN(int dash)
    {                    
        dashPatternList ds = dashPatternList.pic0;
        if (dash == 1) ds = dashPatternList.pic1;
        if (dash == 2) ds = dashPatternList.pic2;      
        return ds;
    }

    private int dashOUT(dashPatternList dash)
    {
        int i = 0;
        if (dash == dashPatternList.pic1) i = 1;
        if (dash == dashPatternList.pic2) i = 2;   
        return i;
    }

And call it:

 pData.DashPattern = dashIN(dashPattern);
 dashPattern = dashOUT(pData.DashPattern);

This method works, but maybe you suggest me more easy way.

Was it helpful?

Solution

You could keep the pictures in an array, so instead of dashIN(dash) you'd write dashIN[dash] (and you don't need to write the dashIN function). You just need to initialize it once with something like this:

DashPattern[] dashIN = new DashPattern[] { 
   dashPatternList.pic0, dashPatternList.pic1, dashPatternList.pic2 };

For the reverse, something like Array.IndexOf(dashIN,mypic) should work.

This way you replace code with data, which tends to be a good thing as it's usually easier to manage. For example now you only have to change one line if you want to change the list of dash patterns, instead of having to change the code in two functions earlier. Plus now it's impossible to make an error that would cause dashOUT(dashIN(dash))!=dash (as would happen if there's a wrong number in the code).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top