Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
imdadhusen Avatar asked Jun 29 '11 05:06

imdadhusen


People also ask

Can we convert list to object?

A list can be converted to a set object using Set constructor. The resultant set will eliminate any duplicate entry present in the list and will contains only the unique values. Set<String> set = new HashSet<>(list);

What is generic type C#?

Generic means the general form, not specific. In C#, generic means not specific to a particular data type. C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.


1 Answers

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.

like image 147
Jon Skeet Avatar answered Oct 20 '22 22:10

Jon Skeet