How can I define a generic table property in a base class?

Answered How can I define a generic table property in a base class?

  • Monday, October 20, 2008 6:17 AM
     
     

    I have created a base page class that all other pages in my site inherit from.  I am trying to define a generic table property so that this property can be loaded and saved into a session variable during each page process. 

     

    I have a DataContext of tables that include Products & Photos.

     

    I am able to do this:

     

    protected Product m_Product {get; set;}

     

    but not this:

     

    protected T m_Entity {get; set;} // error on 'T'

     

    I am calling a load and save method during the page process as such:

     

    protected T LoadEntity<T>()

    {

    if (Session["PageEntity"] == null)

    return default(T);

    return (T)Session["PageEntity"];

    }

     

    protected void SaveEntity<T>(T entity)

    {

    Session["PageEntity"] = entity;

    }

     

    Ideally I would like to execute these methods in the base class on m_Entity to load and save the current state of the table.

     

    Is this possible? 

     

All Replies

  • Monday, October 20, 2008 8:52 AM
     
     Answered
    Hi

    Yes it is possible, but to use a generic type as a module wide variable you need to define the generic type on the class level. Like:

    public class EntityBucket<T> {
    protected T m_Entity {get; set;}

    protected T LoadEntity()
    {
        if (Session["PageEntity"] == null)
        return default(T);

        return (T)Session["PageEntity"];
    } 

    protected void SaveEntity(T entity)
    {
        Session["PageEntity"] = entity;
    }
    }
  • Monday, October 20, 2008 10:20 AM
     
     

    Thank you Patrik!  That works perfectly for me and solves the problem I have 100%.

     

    David

  • Monday, October 20, 2008 12:55 PM
     
     
    Great Smile Glad I could help!