Could somebody kindly explain this to me, in simple words:
there is no way to constrain a type to have a static method. You cannot, for example, specify static methods on an interface.
many thanks in advance to you lovely people :)
With generics, you can add a constraint that means the generic-type supplied must meet a few conditions, for example:
where T : new()
- T
must have a public parameterless constructor (or be a struct
)where T : class
- T
must be a reference-type (class
/ interface
/ delegate
)where T : struct
- T
must be a value-type (other than Nullable<TSomethingElse>
)where T : SomeBaseType
- T
must be inherited from SomeBaseType
(or SomeBaseType
itself)where T : ISomeInterface
- T
must implement ISomeInterface
for example:
public void SomeGenericMethod<T>(T data) where T : IEnumerable {
foreach(var obj in data) {
....
}
}
it is SomeBaseType
and ISomeInterface
that are interesting here, as they allow you to demand (and use) functions defined on those types - for example, where T : IList
gives you access to Add(...)
etc. HOWEVER! simply: there is no such mechanism for things like:
so: you can't demand those, and you can't use them (except via reflection). For some of those dynamic
can be used, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With