views:

222

answers:

1

Just I am learning Generics.When i have an Abstract Method pattern like :

//Abstract Product
interface IPage
{
    string pageType();
}

//Concerete Product 1
class ResumePage : IPage
{
    public string pageType()
    {
        return "Resume Page";
    }
}

//Concrete Product 2
class SummaryPage : IPage
{
  public string pageType()
  {
    return "SummaryPage";
   }
}

//Fcatory Creator
class FactoryCreator
{
   public IPage CreateOnRequirement(int i)
    {
      if (i == 1) return new ResumePage();
      else { return new SummaryPage(); }
    }
}


//Client/Consumer

void Main()
{

  FactoryCreator c = new FactoryCreator();
  IPage p;
  p = c.CreateOnRequirement(1);
  Console.WriteLine("Page Type is {0}", p.pageType());
  p = c.CreateOnRequirement(2);
  Console.WriteLine("Page Type is {0}", p.pageType());
  Console.ReadLine();
}

how to convert the code using generics?

+1  A: 

You can implement the method with a generic signature and then create the type passed into the type parameter.

You have to specify the new() condition though.
This means it will only accept types that have an empty constructor.

Like this:

public IPage CreateOnRequirement<TCreationType>() where TCreationType:IPage,new()
{
    return new TCreationType();            
}
Simon P Stevens
where TCreationType : new(), IPage
Nagg
@Nagg: Yes, thanks. Missed that.
Simon P Stevens
Thanks Simon for spending your time.
nanda
new() constraint must be placed at last i mean IPage,new() instead new(),IPage.
nanda
Edited according to comments.
Alex Bagnolini
@Alex Bagnolini: Thank.
Simon P Stevens