views:

45

answers:

1

Hey guys I cant manage with this code. The idea is to return default English alphabet in case of erroneous create method execution. Thanks.

An idea to override explicit operator is good, but i cant imagine an implementation of casting.

namespace trie
    {
        class AlphabetFactory<T> where T: IConvertible
        {
            public Alphabet<char> SetDefaultAlphabet()
            {
                var list = new char[26];
                for (var i = Convert.ToInt32('a'); i <= Convert.ToInt32('z'); i++)
                    list[i] = Convert.ToChar(i);
                return new Alphabet<char>(list);
            }

            public Alphabet<T> Create(params T[] list)
            {
                if (list != null)
                    return new Alphabet<T>(list);
                else
                    return SetDefaultAlphabet();    // <- This is not correct   
            }
        }
    }
A: 

The only way I can think to accomplish what you want is to make Alphabet<T> inherit from a non-generic abstract base, or else implement a non-generic interface. Then your code might look something like this:

interface IAlphabet {
    // ?
}

class Alphabet<T> : IAlphabet {
    // stuff
}

class AlphabetFactory {
    // ...

    IAlphabet Create<T>(params T[] list) where T : IConvertible {
        if (list != null)
            return new Alphabet<T>(list);
        else
            return SetDefaultAlphabet();
    }

    // ...
}

This would make client code using your AlphabetFactory a bit more cumbersome to use, though:

int[] integers = GetIntegers(); // let's say this might be null

var alphabet = myAlphabetFactory.Create(integers);

var integerAlphabet = alphabet as Alphabet<int>;
if (integerAlphabet != null) {
    // do stuff with integerAlphabet
} else {
    // alphabet is an IAlphabet, but not an Alphabet<int>
}
Dan Tao