tags:

views:

194

answers:

2
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());
    }
}
A: 

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

}
thecoop
I wasn't actually trying to do anything. I had to take an exam on C# today and I came up with a question/code very similar to what I suggest. I wasn't sure of the answer so I thought I would ask here. Unfortunately, I can't remember the code exactly as it was.
dotnetdev
A: 

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.

JaredPar
If you look at the method, the "T" is actually a method parameter. It has the same name as the class's parameter, and so will generate a warning. However, it's not actually illegal here.(although I would recommend renaming it to U, like you suggest)
Scott Wisniewski
@Scott, I actually thought C# would issue an error there vs. a warning. Weird :(
JaredPar