How to specify generic type c?
I tried to indicate this general, but I get a few 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, ":" immediately after V on the first line produces 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 clearly wrong with my shared code?
Update:
I made changes, and now the code 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 a derived class:
public void AddOrUpdate(Account account) { base.AddOrUpdate<Account, IAzureTable<Account>>(account, _accountRepository); }
You will 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 restrictions for one type parameter. Please note that I added type parameters to the method, otherwise the compiler will look for T
and V
as normal types and will not understand why you tried to restrict them.
A few things seem wrong.
1) As @Jon said, you need separate where
clauses
2) You need to determine the generics of the method:
public void AddOrUpdate<T,V>(T item, V repo) where ....
3) You are trying to call a method of type V
, not an instance of this type of repo
. those. this is:
V.AddOrUpdate(item);
it should be
repo.AddOrUpdate(item);