1

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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Thanks. I don't need S. But type G is not covariant, so I cannot accept smth like G<object>. Do you know if there is any philosophical reason why solving this is not possible or is it just a tech limitation of C#?
The compiler needs to know what S will be. The code will be different if S is a value type compared to a reference type, and even different for different value types.
0

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

1 Comment

Does not seem to work with constructor. Am I missing something?
0

User following implementation:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.