1

I have a class called Location and it can either be Location<IClub> or Location<IRestaurant>.

I get a record from a database and that record then specifies whether this location is a restaurant or a club.

I need to create Location based on a string value within the record.

I have tried doing this;

        object topLoc = null ;

        if (record.type == "club")
            topLoc = new Location<IClub>();

but I cannot access any of Location's properties.

I also can't create the object in an if statement as when you leave the if the object will be out of scope.

2
  • Do you have a common interface that you can use for both types, something like ILocation instead of object? Commented Dec 21, 2011 at 4:33
  • I can do but then how do i add the iClub or IRestaurant interface to the object? Commented Dec 21, 2011 at 4:34

1 Answer 1

2

It sounds like generics are not the tool you need. Rather than using generics to annotate the kind of location, consider using an enum.

public enum LocationKind
{
    Restaurant,
    Club
}

Location location = new Location(LocationKind.Club);
// set up & use location as you see fit; expose the LocationKind through a
// property or something else along those lines
Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm, yeah. As a last resort but that would involve quite a bit of refactoring of "legacy" code. <shudder>
@griegs, you can otherwise use the dynamic keyword as the type of topLoc, but that means byebye static typing for that part of your code. (Also, it requires you to use the .NET Framework 4 or better.)
@griegs, yet another option is to create a non-generic superclass of Location (IIRC you can call it Location too) that will have all the fields that don't depend on the generic type; though I would recommend this approach only as a temporary measure because you usually don't want to add meaningless inheritance.
I know you're right, and I suspect the best avenue is the Enum method but just the thought of all the rework is driving me to the nearest pub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.