views:

81

answers:

3

Hey All,

I've asked this question yesterday and got lots of good answers, only I just realized my question was wrong and here I want to rephrase it.

I have this interface

public interface IFoo<T>
{
   T Value();
}

With this members

public class Bar : IFoo<string>
{
   string Value(){return "test";}
}
public class Bar2 : IFoo<int>
{
   int Value(){return "1";}
}

This works perfectly, but now I want to make a class that has a property that can be either Bar or Bar2 so like this

public class Test
{
  IFoo test;
}

Only this will not compile because Ifoo needs to have a generic type. Only I don't know in advance whether I will use Bar2 or Bar.

I hope I explained it well, but if not, I'll try to make it more clear.

Explaination

I'm trying (just for fun's sake) to create a Dicom api (medical imaging etc). Part of the dicom standard are some ValueRepresentations (VR's). These are types that are used to store (meta)information of the image.

Such VR's are for example: AgeString, Date, UnsignedShort, SequenceOfItems.

For all of these VR's I want to have some methods that all of them have to implement (encoding etc). But I all want them to be able to store a value. Whether this is a Int, or a DateTime or a String, shouldn't this be put in the Interface?

+4  A: 

You have to make your Test class generic as well:

public class Test<T>
{
   IFoo<T> test;
}
BFree
Thanks, this did the trick. Only I just realised that I have to ask a different question :P
Timo Willemsen
+1  A: 

You want to use two different classes the same way, but you let them implement different interfaces (different by their type parameter). Why?

Do you really need to strictly specify what type the return value of the method is? How would you handle that different return types in your Test class? Think about it and you may realize that it is enough to return an object. Otherwise you need to make the Test class generic as well.

Best Regards
Oliver Hanappi

Oliver Hanappi
I gave an explaination in my original post. ^^ Thanks a lot!
Timo Willemsen
+1  A: 

You can always make a general interface, in the same way that there's an IEnumerable<T> and an IEnumerable.

public interface IFoo
{
    object Value();
}

Implementation

public class Bar : IFoo<string>, IFoo
{
   public string Value(){return "test";}
   object IFoo.Value(){return Value();}
}
public class Bar2 : IFoo<int>, IFoo
{
   public int Value(){return 1;}
   object IFoo.Value(){return Value();}
}

Test

IFoo b = new Bar();
IFoo b2 = new Bar2();
Console.WriteLine(b.Value());
Console.WriteLine(b2.Value());
Cameron MacFarland
I tried something similar, but you're cheating a little, aren't you? Remember that `IEnumerable<T> : IEnumerable`, but your `IFoo<T>` does not implement `IFoo` - that is, every class that implements `IFoo<T>` must also *implicitly* implement `IFoo`.
Kobi
It's not cheating, I just forgot. :) IFoo<T> doesn't have to implement IFoo but it probably should.
Cameron MacFarland