0

I'm trying to pass a object type to a method. I'm doing this for my CRUDRepository that's inherited by others repositories, but i can't figure out how to know with type i'm handling.

For example:

    public PageOf<Entity> GetPageOfEntity(int pageNumber, int pageSize)
    {
    // Here i need to work with the entity type to make calls to database  
    }

The Entity is a object that's inherited by other entities (user, products, etc) and this method is returning a paged result. I'm doing this to avoid creating a GetPageOf method for each entity that i've.

What's the proper way to pass to the method the object type that i want to deal in paged results?

Edit:

Here's a example of the Entity

     public abstract class Entity 
     {
     public virtual long Id { get; set; }
     public virtual DateTime Created { get; set; }
     }

And the user object:

     public class User : Entity
     {
     public string FirstName { get; set; }
     }

As i'm trying to write a single class to handle some crud operations, i need to know in the method what object i'm using (but i'm trying to now create one method for each object type)

Thanks

Gui
  • 9,555
  • 10
  • 42
  • 54
  • little more code & details would help. Are you looking for passing a type? probably you can have an inbound argument of type `T` and then perhaps instantiate and do a GetType() on instance to check what type it is and build that typed pageOf and return. – Sanjeevakumar Hiremath Apr 01 '11 at 08:25
  • I think what he's asking is how to resolve T back to a table in the data context.. – MattDavey Apr 01 '11 at 08:28
  • Possible duplicate of http://stackoverflow.com/questions/10955579/passing-just-a-type-as-a-parameter-in-c-sharp – Michael Freidgeim Jun 16 '13 at 03:23
  • Not really, i've asked this before. Check the dates. – Gui Jun 16 '13 at 19:04

2 Answers2

5

Make the method generic:

public PageOf<TEntity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)
    where TEntity : Entity
{
    Type entityType = typeof(TEntity);
    ...
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

I am not sure, I understand your question correctly, but can't you just use a generic parameter?

public PageOf<Entity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize) 
    where TEntity : Entity
{
// Here i need to work with the entity type to make calls to database  
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • I'm sorry but my English isn't perfect (i'm Portuguese) and sometimes i really can't express myself! But yes, generic parameter is what i need. Thanks ;) – Gui Apr 01 '11 at 08:34