Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I get a generic in C# to return a value?

I already use the following generic to add or update a record:

    public void AddOrUpdate<T, V>(T item, V repo)
        where T : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
        where V : IAzureTable<T>
    {
        try
        {
            repo.AddOrUpdate(item);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding");
            throw _ex;
        }
    }

What I need is a similar generic that will allow me to retrieve a record and implement the following as a generic:

public Account GetAccount(string pk, string rk)
        {
            var account = _accountRepository.GetPkRk(pk, rk);
            if (account == null)
            {
                _ex.Errors.Add("", "Account " + rk + " does not exist");
                throw _ex;
            }
            return account;
        }

Can someone explain how I could make a generic that returns an instance of the class T. I am not familiar with how to make generics return values. I think I can code up the generic but I am just not sure about how to return a value.

Upvotes: 1

Views: 105

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176906

public T methodname<T>()
{
  return TypeTobject;
}

You can also look in to this issue : Generic Method Return Type Casting Problem

Upvotes: 1

Luke Baulch
Luke Baulch

Reputation: 3656

public T GetClassT<T>()
{
    // do your processing here
    var someObject = DoSomeProcessHere();

    // ensure that your return object is of type T
    return (T)someObject;
}

Upvotes: 1

Related Questions