imdadhusen
imdadhusen

Reputation: 2494

How to convert T to object

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.

Upvotes: 8

Views: 26754

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

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.

Upvotes: 18

Related Questions