Search code examples
c#generic-programming

C#, Generic, access to property


I'm using Generic Classes in C# and I wanna access to Text or any other property of the object, how can I do that?

class Methods<T> where T : class
{ 
    bool insertDocument(T content)
    {
        return client.search(content.Text);
    }
}

and i don't want to use Interface


Solution

  • You can't, you're specifying as the only constraint that 'T' should be a 'class', not all classes have a 'Text' property, so you cannot access that property. You're simply misusing generics (they're not a way to make a single function work with everything, but a way to make a single function work with a subset of object types that share a common behavior that you want to exploit, here you're not specifying a subset, so you end up with a fairly useless 'T' type)