frosty
frosty

Reputation: 5370

how to return type t from a method

I have the following method that sets a few properties of IEntity. My general idea is that i would like all of my classes that implement IEntity to use this helper. The issue is that this returns IEntity and not Type T. How would do that?

    public static IEntity Create(IEntity entity, Company company)
    {
        entity.Company = company;
        entity.Key = Guid.NewGuid();
        entity.Created = DateTime.Now;
        entity.Modified = DateTime.Now;
        entity.ModifiedByUserName = "xxx";
        entity.CreatedByUserName = "xxx";
        return entity;
    }

I currently call the class from my controller like so. ( TaskOrder implements IEntity )

var taskOrder = EntityHelper.Create(TaskOrder(), company);

Upvotes: 0

Views: 3108

Answers (1)

escargot agile
escargot agile

Reputation: 22379

Read about generics in C#, there's a lot of material on the web.

Here is an example based on your code:

public static T Create<T>(T entity, Company company) where T : IEntity
{
    entity.Company = company;
    entity.Key = Guid.NewGuid();
    entity.Created = DateTime.Now;
    entity.Modified = DateTime.Now;
    entity.ModifiedByUserName = "xxx";
    entity.CreatedByUserName = "xxx";
    return entity;
}

Upvotes: 10

Related Questions