views:

242

answers:

3

Hi,

I have a method:

 public void StoreUsingKey<T>(T value) where T : class, new() {
  var idModel = value as IIDModel;
  if (idModel != null)
   Store<T>(idModel);

  AddToCacheUsingKey(value);
 }

that I would like to optionally call the following method, based on the value parameter's implementation of IIDModel.

 public void Store<T>(T value) where T : class, IIDModel, new() {
  AddModelToCache(value);
 }

Is there a way to tell Store<T> that the value parameter from StoreUsingKey<T> implements IIDModel? Or am I going about this the wrong way?

Rich

Answer

Removing the new() constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated.

+4  A: 

You already are. By putting the IIDModel constraint on the Store<T> method, you're guaranteeing, that the value parameter implements IIDModel.

Oh, ok I see what you're saying now. How about this:

public void StoreUsingKey<T>(T value) where T : class, new() {
                if (idModel is IIDModel)
                        Store<T>((IIDModel)idModel);

                AddToCacheUsingKey(value);
        }

Edit yet again: Tinister is right. This by itself won't do the trick. However, if your Store method looks like what Joel Coehoorn posted, then it should work.

BFree
But the StoreUsingKey<T> method doesn't have this constraint. How do I selectively call Store<T>? The example above errors with "cannot convert from 'IIDModel' to 'T'".
kim3er
This doesn't seem to work: 'IIDModel' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Store<T>(T)'
Tinister
Sorted it, the class constraints were red herrings. I was being overly restrictive. By removing the class constraint from both methods, the code starts working. Thanks for your help.
kim3er
By "class", I mean "new()".
kim3er
+2  A: 
public void Store(IIDModel value) {
    AddModelToCache(value);
}
Joel Coehoorn
Sorry, I should have been more explicit. The AddModelToCache method is also generic in nature.
kim3er
+1  A: 

Removing the new() constraint from each method allows the code to work. The problem was down to me trying to pass off an interface as an object which can be instantiated.

kim3er