Of which elements does Generics allow parameterization by type?

This is a question from some tests. Question is "Of which elements does Generics allow parameterization by type?" and 5 variants of answers:

  1. Classes
  2. Structs
  3. Methods
  4. Events
  5. Fields

On first glance question is very easy, but I'm not sure about correct answers. Let's step by step.

  1. Classes.

We can write something like

class SuperKeyType<K, V, U>
    where U : System.IComparable<U>
    where V : new()
{ }

so, Classes can be parameterized by type. The same with Structs.

About methods. We can write the following:

class GenericList<T>
{
    // CS0693 
    void SampleMethod<T>() { }
}

so, methods too.

About Events and Fields:

class Foo<TValue> {
    public string Value { get; set; }
    public TValue TypedValue {
        get {
            return (TValue)Convert.ChangeType(Value, tyepof(TValue));
        }
    }
}

Property is parametrized by type, correct (the same with Events)? But on the following page

Making a generic property

I see the following answer:

Properties, events, constructors etc can't be generic - only methods and types can be generic. Most of the time that's not a problem, but I agree that sometimes it's a pain. Brannon's answer gives two reasonable workarounds.

I this place I ask itself - What means under "parameterization by type" at all? Property above is parametrized by type or not? What is correct answer:

  1. true
  2. true
  3. true
  4. false
  5. false

or

  1. true
  2. true
  3. true
  4. true
  5. true
Jon Skeet
people
quotationmark

Property is parametrized by type, correct (the same with Events)?

No, it's not. There's no type parameter on the property itself - you've got it on the class.

Compare that with your method example:

class GenericList<T>
{
    // CS0693 
    void SampleMethod<T>() { }
}

... which would be clearer as

class NonGenericType
{
    void GenericMethod<T>() { }
}

Note how the type parameter (T) is introduced in the method signature, not on the class.

You can't specify a type parameter for fields, properties, events, constructors or finalizers.

A generic property would have to look something like:

// Not valid: properties can't be generic. But imagine...    
public T Value<T> { get; set; }

Likewise a generic constructor would be something like:

public class Foo
{
    // Not valid: constructors can't be generic. But imagine...
    public Foo<T>(T initializationValue)
    {
        // Note that this isn't constructing a Foo<T> -
        // Foo is a non-generic type. It's only the constructor
        // that is generic.
    }
}

A generic field is even weirder as a concept. What could it possibly mean?

private int field<T>;
...
int x = field<string>;

people

See more on this question at Stackoverflow