Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics: there is no way to constrain a type to have a static method?

Tags:

c#

generics

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 :)

like image 882
Idrees Avatar asked Jun 07 '11 11:06

Idrees


1 Answers

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:

  • constructors with parameters
  • static methods
  • operators / conversions
  • arbitrary methods not defined via a base-type or interface

so: you can't demand those, and you can't use them (except via reflection). For some of those dynamic can be used, though.

like image 124
Marc Gravell Avatar answered Nov 18 '22 20:11

Marc Gravell