Sobes.tech
Junior — Middle

Is it possible to apply generic method types without encapsulating them in generic classes?

sobes.tech AI

Answer from AI

Yes, in C# it is possible to use generic method types regardless of whether the class is generic. That is, a method can have its own type parameters that are not related to the class's type parameters. This allows for creating more flexible methods within both regular and generic classes.

Example:

class MyClass
{
    public void Print<T>(T item)
    {
        Console.WriteLine(item);
    }
}

// Usage
var obj = new MyClass();
obj.Print<int>(123);
obj.Print<string>("text");

Here, the Print method is generic, while the MyClass class is non-generic.