Hey! Use A Method To Get Your SPList!

Well, maybe it is just me, but you should generally use a method in order to get a reference to your SharePoint lists. For example, you are generally getting a reference as such:

  1. using(SPSite mySite = new SPSite("http://server/"))
  2. {
  3. using(SPWeb myWeb = mySite.OpenWeb())
  4. {
  5. SPList myList = myWeb.Lists["MyList"];
  6. }
  7. }

But wouldn’t it be better to use a method?

  1. public static SPList GetList(SPWeb website, string listName)
  2. {
  3. if (website == null)
  4. {
  5. return null;
  6. }
  7. try
  8. {
  9. return website.Lists[listName];
  10. }
  11. catch
  12. {
  13. return null;
  14. }
  15. }

You could then use this between your setting of your web references. I think it is a much better, much more elegant approach when getting a reference to a list, but hell, maybe it’s just me :-)

share save 171 16 Hey! Use A Method To Get Your SPList!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>