rodolfo
rodolfo

Reputation:

problems with generics in C# in parameter

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?

Upvotes: 3

Views: 332

Answers (3)

Kent Boogaart
Kent Boogaart

Reputation: 178820

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

Upvotes: 12

Reed Copsey
Reed Copsey

Reputation: 564931

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.

Upvotes: 0

Lucero
Lucero

Reputation: 60276

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

Upvotes: 4

Related Questions