ptkvsk
ptkvsk

Reputation: 2222

Generic class with unused generic parameter in constructor

I want to do following:

public class My<T>
{
   public My(G<S> g, T t)
   {
       // code that DOES NOT use S in any way
   } 
}

I'm getting 'Cannot resolve symbol S'. Is it possible to do it somehow? And if not, why? I can't change G, it's not my class.

Upvotes: 1

Views: 274

Answers (4)

Nitin Joshi
Nitin Joshi

Reputation: 1668

User following implementation:

public class My<T, S>
{
  public My(G<S> g, T t)
  {
    // Now S will be accessible.
  }
}

Upvotes: 0

AlexH
AlexH

Reputation: 2700

Just declare S explicitly in your method :

public class My<T, S>
{
   public My(G<S> g, T t)
   {
       // code that DOES NOT use S in any way
   } 
}

This will compile (except if you have some conditions on S on G class). You will have to declare what is S in any case when using the My class.

Example will G< S > = Nullable< S > :

public class My<T, S> where S : struct
{
    public My(Nullable<S> g, T t)
    {
        // code that DOES NOT use S in any way
    }
}

With this implementation, you have to define S when using the My class (in that case S is int):

var myVar = new My<string, int>(4, string.Empty);

Upvotes: 0

Sean
Sean

Reputation: 62472

Unlike member function, constructors cannot specify generic types in their declaration. To work around this you'll need to lift the generic type out of the constructor and into the class declaration:

public class My<T,S>
{
   public My(G<S> g, T t)
   {
       // code that DOES NOT use S in any way
   } 
}

This may be a problem if you intend to have various constructors that take additional generic types.

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391346

You need to either:

  1. Remove the need for the <S> or G<S> (ie. replace it with a non-generic type, an interface, etc.)
  2. or Add S as a generic parameter to the type:

    public class My<T, S>
    {
       public My(G<S> g, T t)
       {
           // code that DOES NOT use S in any way
       } 
    }
    

Upvotes: 1

Related Questions