Dawid Dawid - 23 days ago 7
C# Question

c# Cannot implicitly convert type '' to ''

I'am new in C#;
Please tell me what is bad;

MESSAGE: "Cannot implicitly convert type 'Factory.ContactSite' to 'Factory.Site'"

MY code:

class SiteFactory {

public enum SiteType {
Contact, Gallery, Info, News
}

public static Site makeSite(SiteType type) {

switch (type) {

case SiteType.Contact:
{
return new ContactSite(); //create new object
}
case SiteType.Info:
{
return new InfoSite(); //create new object
}
default:
return null;
}
}
}


//-----------------------------------------------------------------

class Site {

public bool generate(String patch) {

System.IO.FileStream f = new FileStream(patch, FileMode.Create);
return true;
}
}


//------------------------------------------------------------
main:

SiteFactory.makeSite(SiteFactory.SiteType.Contact).generate("file.txt");


class 'ContactSite' is currently empty

Answer

I guess what you need to do is derive the classes InfoSite and ContactSite from Site like this:

public class ContactSite : Site
{

}

public class InfoSite : Site
{

}

when you call makeSite to get an Instance you would have to cast it into the right type like this:

InfoSite infSite = SiteFactory.makeSite(SiteFactory.SiteType.Contact) as InfoSite;