This is a question from some tests. Question is "Of which elements does Generics allow parameterization by type?" and 5 variants of answers:
- Classes
- Structs
- Methods
- Events
- Fields
On first glance question is very easy, but I'm not sure about correct answers. Let's step by step.
- 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
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:
- true
- true
- true
- false
- false
or
- true
- true
- true
- true
- true