14836

C#: Multiple type parameters in extensions

Question:

I was trying to create an extension that could slice any array-like class (since slicing is oddly absent in the standard libraries). For example:

public static M Slice<M,T>(this M source, int start, int end) where M : IList<T> { //slice code }

However, the compiled does not attach this method to objects of type M (even though its error message claims that that is what it is looking for). It seems rather to be dependent upon the type parameters of the method itself, e.g. in some manner, but I don't fully understand how things are working.

(yes, one could easily write an example that just works with List, but I'm curious if this is even possible.)

Answer1:

There compiler does not infer the type T automatically for these cases. Even if it wasn't an extension method, you still had to specify the type parameters manually.

For example what if the class was declared as:

class MyNastyClass : IList<int>, IList<double> { }

What would you expect T to be? int or double? As a result, you'll always have to manually call it with the specific parameters:

Slice(myList, 0, 10); // compile-time error, T cannot be inferred. Slice<IList<int>, int>(myList, 0, 10); // works.

The workaround is to remove the type parameter T (no constraints needed here):

public static void Slice<M>(this IList<M> source, int start, int end)

By the way, note that, this is by no means related to the number of parameters. You can have as many type parameters as you like, as long as the compiler can infer them (according to C# specification generic type inference rules). For example, this extension method can be called without specifying type arguments:

public static void SomeMethod<T,U>(this IEnumerable<T> collection, U anotherParameter)

Answer2:

Have you looked at the <a href="http://msdn.microsoft.com/en-us/library/21k0e39c(VS.85).aspx" rel="nofollow">List.GetRange method</a>?

Recommend

  • SNIReadSync executing between 120-500 ms for a simple query. What do I look for?
  • Missing type map configuration or unsupported mapping after auto code generation on the client
  • How to mount dynamically single file component in Vue.js
  • LatLong falls within a given polygon in D3 + Leaflet
  • What's the point of nonfinal singleton objects in scala?
  • Remove every nth element from swift array
  • Git subtree post hook
  • How do I correctly parse a URI query string into a name-value collection in C#?
  • Trouble Attaching Call Back to Unobtrusive Validation Show Error
  • How to create a data template dependent on an XML Attribute?
  • How do I recognize a line break with a switch case that evaluates a char in Java?
  • 'include' of functions in groovy scripts
  • Using $compile in a directive triggers AngularJS infinite digest error
  • Jquery Knockout: ko.computed() vs classic function?
  • Date Conversion from yyyy-mm-dd to dd-mm-yyyy
  • Debug.DrawLine not showing in the GameView
  • x64 applications using gdi+: what are the consequences on performance?
  • NHibernate Validation Localization with S#arp Architecture
  • CSS Linear-gradient formatting issue accross different browsers
  • How can I send an e-mail from a vbs script
  • NetLogo BehaviorSpace - Measure runs using reporters
  • Spring security and special characters
  • Why is the size of this struct 32?
  • Accessing IRQ description array within a module and displaying action names
  • JSON with duplicate key names losing information when parsed
  • Trying to switch camera back to front but getting exception
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • Free memory of cv::Mat loaded using FileStorage API
  • C# - Getting references of reference
  • Hits per day in Google Big Query
  • Angular 2 constructor injection vs direct access
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How do I configure my settings file to work with unit tests?
  • Getting Messege Twice Using IMvxMessenger
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Linking SubReports Without LinkChild/LinkMaster
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Programmatically clearing map cache
  • Binding checkboxes to object values in AngularJs
  • Python/Django TangoWithDjango Models and Databases