GurdeepS
GurdeepS

Reputation: 67283

generic class and generic methods

class test <T> where T : class
{
    public void Write<T>()
    {
        Console.Write(typeof(T).FullName);
    }
}

In the above class, it is possible to pass in a string for the class (test<string> Test = new test<string>) and then int for the method? If so, what is the output? If not, what problems does this cause? I haven't actually tried this, despite using generics (in my own classes) and generic collections, frequently.

The way I write/see generic classes is as follows:

class <T> where T : class
{
    public T Write()
    {
        Console.Write(T.ToString());
    }
}

Upvotes: 1

Views: 5577

Answers (2)

JaredPar
JaredPar

Reputation: 755457

As it was originally written no you cannot. In order to use different types at different points in the class, you must have multiple generic parameters. It is possible to define a different one at the method level and get your sample to work

class Test<T> where T : class {
  public void Write<U>(U arg1) {
    Console.WriteLine(arg1.ToString());
  }
}

Usage

var t = new Test<string>();
t.Write(42);

As Scott pointed out you can use the same named parameter. Although doing so will cause a warning and generally speaking confuse people. It is much cleaner to have distinct names for all generic parameters currently in scope.

Upvotes: 4

thecoop
thecoop

Reputation: 46158

You'll be wanting to declare a type variable in the method separately to the class -

class Test<T> where T : class {

    public void Method<U>(U val) {
        Console.WriteLine(typeof(U).FullName);
    }

}

Upvotes: 0

Related Questions