Adam
Adam

Reputation: 459

C# Inheritance / Interfaces

I have a class Item that is inherited by other classes... Attraction, Business, CommunityEvent. I cannot set the object items the way that I am, it is a syntax error. The Lists can't be assigned like this. What is the best way to go about doing this? Basically, Attraction is an item, but it has a few more properties. Business is an item, but it has a few more properties. ...etc.

public List<Item> GetItems(PageType type)
    {
        List<Item> items;

        switch (type)
        {
            case PageType.Attraction:
                items = new List<Attraction>();
                break;
            case PageType.Business:
            case PageType.ShopAndEat:
                items = new List<Business>();
                break;
            case PageType.Event:
                items = new List<CommunityEvent>();
                break;
            default:
                items = new List<Item>();
                break;
        }

        // TODO: Call Webservice method to get Item



        return items;
    }

Upvotes: 0

Views: 71

Answers (2)

AGB
AGB

Reputation: 2226

I think you may be able to use generics and type restrictions to do some of the heavy lifting for you. How about

using System;
using System.Collections.Generic;

namespace Sample
{
    public class Item
    {
    }

    public class Business : Item
    {
    }

    public class Attraction : Item
    {
    }

    public class Foo
    {
        public List<T> GetItems<T>() where T : Item
        {
            //TODO: based on T, call the appropriate services to populate the list
            return new List<T>();
        }
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            // Examples:
            var foo = new Foo();
            List<Attraction> attractions = foo.GetItems<Attraction>();
            List<Business> businesses = foo.GetItems<Business>();
            List<Item> items = foo.GetItems<Item>();
            //...
        }
    }
}

Actually populating the list with objects that have a few more properties than Item (and accessing those properties) will take you pretty quickly into Co- and Contravariant generics. I would highly recommend Eric Lippert's excellent blog series on that topic.

Upvotes: 2

Russell Hankins
Russell Hankins

Reputation: 1176

You don't need to do

items = new List<Business>();

You can do

items = new List<Item>();

and still add different kinds of items to the items list like

items.Add(new Business());

Your items list can be all different kinds of items.

Upvotes: 0

Related Questions