views:

256

answers:

3

I have class like this:

Class foo<T> 
{
  anotherfoo<T>;

  foo(){}
  foo(foo<T> aFoo)
  { anotherfoo = aFoo; }
}
void main() 
{
foo<string> obj1 = new foo<string>();
foo<int> obj2 = new foo<int>(obj1);
}

This time I get a error: cannot convert from foo<string> to foo<int>.

But I need have in this class "foo" another obj foo of another type, is this possible?

+12  A: 

Your class Foo<T> has a field of type Foo<T>. That means that whatever you choose for your type T will dictate the type of the field.

An alternative might be to provide a non-generic base class (or interface) as such:

public abstract class FooBase
{
}

public class Foo<T> : FooBase
{
    private FooBase _anotherFoo;
    ...
}

HTH, Kent

Kent Boogaart
+4  A: 

You can have Foo implement interfaces which are not generic and expose non-generic functionality in those.

interface IFoo {
  // add whatever you need here
}

class Foo<T>: IFoo {
  IFoo anotherfoo;

  Foo(){}
  Foo(IFoo aFoo)
  { anotherfoo = aFoo; }
}

void main() {
  Foo<string> obj1 = new Foo<string>();
  Foo<int> obj2 = new Foo<int>(obj1);
}
Lucero
A: 

Another option is to restrict your type T to IConvertible.

If you do this, you could add a method that constructed a foo of a specific type using IConvertible.ToType to convert it directly to your type.

This would work for string and int, and any other type which implemented IConvertible, but only those types.

Reed Copsey