tags:

views:

37

answers:

3

I want to pass a converter to a method, and the constraint must be that the converter always gets a string as argument. I tried the following, but it won't compile:

class Test
{
   public void Foo(string val, Converter<Tin,Tout> conv)
        where Tin:string
   {
      myObj = conv(val);
   }
}
+1  A: 

Whenever a function signature should carry a generic argument, or an argument with a generic type parameter, that type parameter must be part of the method declaration and the method becomes generic itself.

Especially, the generic type arguments you want to constrain must be part of the method signature of Foo.

Try it this way:

class Test 
{ 
   public void Foo<Tout>(string val, Converter<string, Tout> conv) 
   { 
      myObj = conv(val); 
   } 
} 
Johannes Rudolph
That wont compile. String cannot be used as a constraint.
GenericTypeTea
Helloooooooooooooooooo!!!! (GenericTypeTea beat me too it!)
leppie
It now tells me that string would be not valid constraint and that only interfaces or non-sealed classes are applicable.
codymanix
Ok, I forgot about the non-sealed constraint. Edited accordingly.
Johannes Rudolph
+1  A: 

Your code nonsensical.

where Tin:string is not valid. Fix that, and add the generic parameters to your method.

leppie
What is nonsensical about that? Beside the fact that it doesn't compile, but this is part of the question. I want to constrain the converter in a way so that it always takes string but may return anything.
codymanix
@codemanix - why do you need to constrain it to string when the Converter can just take string as the first parameter?
GenericTypeTea
@codemanix: If can only be `string`, why not just use `string`. It cant be anything else.... There is no need for a generic parameter for `Tin` in the first place. See @GenericTypeTea 's answer above.
leppie
+2  A: 

What's the point of constraining Tin if it's always going to be a string?

class Test 
{ 
   public void Foo<Tout>(string val, Converter<string,Tout> conv) 
   { 
      myObj = conv(val); 
   } 
} 

Just get rid of the Tin type and use string in your Converter. I think you're over-complicating things.

You cannot use string as a generic constraint as it's a sealed class. This makes perfect sense as nothing can inherit from string so why add a constraint for string?

I.e. If you COULD inherit from string:

public SuperString : string

Then you could use string as a constraint and pass through SuperString as Tin. However you CANNOT do this as string is a sealed class. Therefor the only object you could pass to Tin is String anyway.

Because of this, you may as well get rid of Tin and use the code I wrote above.

GenericTypeTea