2

I'm reading a book "C# in depth" by Jon Skeet and there is a part that confuses me:

Methods and nested types can be generic, but all of the following have to be nongeneric:

  • Fields
  • Properties
  • Indexers
  • Constructors
  • Events
  • Finalizers

I tested and fields (a variable in a class) can be generic, am I not understanding? It makes me doubt about the others.

1 Answer 1

4

Classes and methods can introduce a new generic type parameter, the others in that list can be defined based on that type parameter, but cannot introduce a new one.

This is all fine;

class ClassName<T>{ private T FieldName; private T PropertyName { get; set; } private R GenericMethod<R>(T t, R r) { ... } } 

But not;

class ClassName{ private T FieldName<T>; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now I understand why it said: "For type members, it’s slightly more confusing; some members may look like they’re generic because they use other generic types. Remember that a declaration is generic only if it introduces new type parameters."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.