-1

I have a generic method that it takes a type T of a sapclient method but when I want to initialize it, it initializes as object instead of the actual class. How is it possible to initialize it and pass the username and password as it requires it?

public static Auth<T>(string username, string password) where T : new()
{
    T client = new T(binding, endpointAddress)
    client.ClientCredentials.UserName.UserName = username
    client.ClientCredentials.UserName.Password = password
}

I tried that code but it always gives an error saying

cannot create an instance of the variable type 'T'

Sandra Rossi
  • 11,934
  • 5
  • 22
  • 48
  • 1
    There's no easy way to achieve this without Reflection. Can you use an interface with a `Create` method or pass a `Func` to the method to create `T` outside? There are other ways, of course, depending on the constraints you have – Camilo Terevinto Aug 19 '21 at 17:21
  • 2
    What is the purpose of the generic type argument? What are the possible values for `T`? Would I be allowed to call `Auth(uid,pwd)`? – John Wu Aug 19 '21 at 17:24
  • This cannot currently be done in C#. The parameterless form of a constructor is the only one that's currently supported by the [`new` constraint](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint). There are various flavors of work-arounds, but to help you figure out which one is most appropriate would involve knowing a lot more about your app. The solution may involve refactoring your code to use factories and such. – StriplingWarrior Aug 19 '21 at 17:25
  • Your method is missing a return type – Rufus L Aug 19 '21 at 17:40

1 Answers1

-1

You haven't guaranteed that type T has a constructor with two arguments of whatever types binding and endpointAddress are. Your new() constraint ensures that T will have a constructor with no arguments, but says nothing about any other constructors or lack thereof.

For example, it's valid to call your method, as it is defined, as such: Auth<int>("username", "password"), since int is a value type (and all value types inherently have a parameterless constructor which initializes all of their fields to their default values). But int doesn't have a constructor with two arguments. This contradiction is why your code won't compile.

I don't think it's possible, in general, to call a non-empty constructor on a generic type. Constructors aren't inherited and there are no other ways to constrain constructors aside from the new() constraint. Are you sure you want to be using generics?

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34