codymanix
codymanix

Reputation: 29490

how to pass a converter (constraints not applicable for generic arguments)

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

Upvotes: 1

Views: 130

Answers (3)

djdd87
djdd87

Reputation: 68506

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.

Upvotes: 2

Johannes Rudolph
Johannes Rudolph

Reputation: 35741

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

Upvotes: 1

leppie
leppie

Reputation: 117280

Your code nonsensical.

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

Upvotes: 1

Related Questions