4

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?

2
  • Why does the class have to be generic at all? Commented Apr 9, 2009 at 14:10
  • How do you expect the runtime to cast a string to integer? a conversion needs to exist, most likely you want to parse a string number to a real number. Commented Apr 9, 2009 at 14:14

3 Answers 3

12

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;
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

4

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);
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.