How to convert T to object

I get an error for converting T to Entity

public T Add(T entity) { CAFMEntities db = new CAFMEntities(); db.TabMasters.AddObject((TabMaster)entity); db.SaveChanges(); return entity; } 

This gives me an error:

Cannot convert type 'T' to 'CAFM.Data.EntityModel.TabMaster'

Thanks.

+4
source share
1 answer

Well, how do you want to apply the transformation? Where is the T declared? You can change it so that you have:

 class WhateverClass<T> where T : TabMaster 

at this moment you do not need a throw. Or, if you cannot hold back T , you can use:

 db.TabMasters.AddObject((TabMaster)(object) entity); 

Alternative is

 db.TabMasters.AddObject(entity as TabMaster); 

although I personally am not so keen on it - I prefer a more rigorous cast check.

+11
source

All Articles