Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generics in Interfaces

How do I allow my CookieData to be generic in the following code? I get an compile-time error on the declaration of ICookieService2.

public struct CookieData<T>
{
    T Value { get; set; }
    DateTime Expires { get; set; }
}

public interface ICookieService2: IDictionary<string, CookieData<T>>
{
   // ...
}

My error is:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

I am wanting ICookieService2 to have generic data inserted into it. Thanks!

Edit Won't that lock me into a single T for the construction of any ICookieService2?

Edit 2 What I am trying to do is the following:

CookieData<int> intCookie = { Value = 27, Expires = DateTime.Now };
CookieData<string> stringCookie = { Value = "Bob", Expires = DateTime.Now };

CookieService2 cs = new CookieService2();
cs.Add(intCookie);
cs.Add(stringCookie);
like image 478
Daniel A. White Avatar asked Jun 01 '09 23:06

Daniel A. White


2 Answers

It looks like you have 3 options here

Make ICookieService2 generic

public interface ICookieService2<T> : IDictionary<string, CookieData<T> {
...
}

Create a non-generic base class for CookieData and use that in the interface

public interface ICookieData {}
public class CookieData<T>: ICookieData{}
public interface ICookieService2 : IDictionary<string, ICookieData> {}

Pick a concrete implementation

public interface ICookieService : IDictionary<string, CookieData<int>> {}
like image 173
JaredPar Avatar answered Oct 23 '22 02:10

JaredPar


You must make ICookieService2 generic as well:

public interface ICookieService2<T>: IDictionary<string, CookieData<T>>
{
   // ...
}
like image 39
Lasse V. Karlsen Avatar answered Oct 23 '22 02:10

Lasse V. Karlsen