By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,458 Members | 1,435 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,458 IT Pros & Developers. It's quick & easy.

Using Interfaces: First Time

P: n/a
I have a generic class similar to below that is responsible for returning
classes as Interfaces, where IBook and ICard are known interfaces.
public sealed class StoreManager {

private StoreManager() { }

public IBook GetBook() {

return (IBook) new Book();
}
public ICard GetCard() {

return (ICard) new Card();
}

}
The question I have is do I type cast and return interfaces in the
StoreManager class as above and grab them like this:

IBook _myBook = StoreManager.GetBook();
or
should for example GetBook look like this:

public Book GetBook() {

return new Book();

}

and I grab it like this (doing the type casting now):

IBook _myBook = (IBook)StoreManager.GetBook();
I hope I am making sense.
Best Regards,

Dave

Nov 15 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Hi Dave

">
public sealed class StoreManager {

private StoreManager() { }

public IBook GetBook() {

return (IBook) new Book();
}
public ICard GetCard() {

return (ICard) new Card();
}

}
Probably you want to make GetBook and GetCard *static* otherwise you can't
use them because the constructor is *private* (in addition the class is
sealed) which means you cannot instantiate the class. Unless , of course,
you provide some special static method for instantiating it. But what can be
seen from the rest of your code you want them *static*
The question I have is do I type cast and return interfaces in the
StoreManager class as above and grab them like this:

IBook _myBook = StoreManager.GetBook();
Since you have defined interface IBook and the method is called GetBook I
believe it makes more sence to use the format above. With the clarification
that you don't have to cast Book instance explicitly to IBook. If Book class
implements IBook interface all Book objects are IBook as well.

public IBook GetBook() {

return new Book();
}

should for example GetBook look like this:

public Book GetBook() {

return new Book();

}


In this case you return objects that exposes more functionality then a book
user needs to have. Furthermore, in future you may decide to create not Book
objects but objects of some other class that implements IBook interface.
Imagin that the new class inherits form some other class (say Control) and
due to the single inheritance it cannot be Book as well. Then you will go
for the first case, but you have to change some part of your code

For me the case where GetBook returns IBook makes more sence.

HTH
B\rgds
100
Nov 15 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.