How to convert T to object
22,073
Well, how do you want the conversion to apply? Where is T declared? You may be able to change it so that you have:
class WhateverClass<T> where T : TabMaster
at which point you don't need the cast. Or if you can't constrain T
, you can use:
db.TabMasters.AddObject((TabMaster)(object) entity);
An alternative is:
db.TabMasters.AddObject(entity as TabMaster);
although personally I'm not as fond of that - I prefer the stricter checking of the cast.
Author by
imdadhusen
Aspiring for a challenging carrier wherein I can learn, grow, expand and share my existing knowledge in meaningful and coherent way.
Updated on June 29, 2020Comments
-
imdadhusen almost 4 years
I am getting error to convert T to Entity
public T Add(T entity) { CAFMEntities db = new CAFMEntities(); db.TabMasters.AddObject((TabMaster)entity); db.SaveChanges(); return entity; }
It is giving me an error:
Cannot convert type 'T' to 'CAFM.Data.EntityModel.TabMaster'
Thanks.
-
Jon Skeet almost 13 years@abatishchev: Apparently so, although of course then you don't get as good checking. Will add that in as an option.
-
Admin almost 13 years@abatischev Not with your post as is:
as
only works with reference types, butT
is not constrained as such ... now ifwhere T : class
(or otherwise constrained to another reference type), then yes. -
Jon Skeet almost 13 years@pst: Nope, you don't need to constrain T in order to use
as
. I've just tried it. -
Admin almost 13 years@Jon Skeet
void x<T>() { return null as T; } void Main () { x<string>(); }
gets me "The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint" in LINQPad4. -
Admin almost 13 yearsWell, duh.
TabMaster
is simply a reference type. Underwhelming explanation. -
Jon Skeet almost 13 years@pst: That's trying to convert to
T
- the OP is trying to convert fromT
. I'm not sure where your last comment is aimed...