Generic class and generic methods

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

      

In the above class, is it possible to pass a string for the ( test<string> Test = new test<string>

) class and then an int for the method? If so, what is the result? If not, what problems will this cause? I haven't actually tried this despite frequent use of generics (in my own classes) and shared collections.

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

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

      

+1


a source to share


2 answers


As it was originally written, you can't. To use different types at different points in a class, you must have several common parameters. You can define something else at the method level and get a sample to work with

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

      

Using



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

      

As Scott pointed out, you can use the same parameter. Although it will lead to a warning and, generally speaking, confuses people. It is much cleaner to have different names for all the common parameters currently in scope.

+3


a source


You will need to declare the type variable in the method separately for the class -



class Test<T> where T : class {

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

}

      

0


a source







All Articles