Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a generic with a where?

Tags:

c#

I tried to specify this generic but I am getting multiple errors:

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

For example the ":" just after the V on the first line gives an error:

Error   3   ; expected

plus other errors:

Error   2   Constraints are not allowed on non-generic declarations 
Error   6   Invalid token ')' in class, struct, or interface member declaration 
Error   5   Invalid token '(' in class, struct, or interface member declaration 
Error   7   A namespace cannot directly contain members such as fields or methods   
Error   8   Type or namespace definition, or end-of-file expected

Is there something obviously wrong with my generic coding ?

Update:

I made changes and the code now looks like this:

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

Calling it from the derived class:

    public void AddOrUpdate(Account account)
    {
        base.AddOrUpdate<Account, IAzureTable<Account>>(account, _accountRepository);
    }
like image 454
Samantha J T Star Avatar asked Dec 19 '11 09:12

Samantha J T Star


2 Answers

You need a second where for V:

public void AddOrUpdate<T, V>(T item, V repo)
    where T : IAuditableTable
    where V : IAzureTable<TableServiceEntity>

Each where lists the constraints for a single type parameter. Note that I've added the type parameters to the method as well - otherwise the compiler would be looking for T and V as normal types, and wouldn't understand why you were trying to constrain them.

like image 105
Jon Skeet Avatar answered Sep 19 '22 11:09

Jon Skeet


A few things seem wrong.

1) As @Jon said, you need separate where clauses

2) You need to define the generics on the method:

public void AddOrUpdate<T,V>(T item, V repo) where ....

3) You are trying to call a method on the type V not the instance of this type repo. ie, this:

V.AddOrUpdate(item);

should be

repo.AddOrUpdate(item);
like image 29
Jamiec Avatar answered Sep 22 '22 11:09

Jamiec