views:

99

answers:

1

I'm modelling a list of strongly typed database keys. Some will be ints, some strings, some guids etc.

EDIT They are strongly typed in the sense that some of the keys will contain integer values, some strings, some uids etc.

So if my class for the Key was "Key" and my list was List<Key> I'm looking for how to implement the strongly typed aspect. I don't want to use generics as I don't think its appropriate here (prove me wrong though).

I'm thinking of making "Key" and abstract class and making each subclass implement the strongly typed aspect. But this will be messy as well. (see below)

Does anyone have any better ideas?

public abstract class RowKey
{
    public string DbName { get; set; }

    public abstract object GetTypedValue();
}

public class IntegerRowKey: RowKey
{
    public override object GetTypedValue()
    {
        return 1;
    }
}
+2  A: 

Why do you think generics are inappropriate here? They were pretty much invented for this scenario:

public class RowKey<T>
{
    public string DbName { get; set; }
    public T GetValue():
}
// Now use RowKey<int>, RowKey<string>, RowKey<Guid>, etc.

Having an abstract base class that returns object kind of destroys the whole idea of being strongly-typed, no?

edit: ah, I see what you're getting at. Have a look at this question.

tzaman
I agree with the returning a type of object ruining the strong typing. However if I want to have a list of RowKeys is would they not all have to be of the same type e.g. I couldn't mix RowKey<int> and RowKey<string> in the same list
AJM
@AJM: see edit. :)
tzaman