1

I think I remember reading a long time ago that in C#3 extension methods could only be applied to primitive types and interfaces; and that in C#4 they could be used to extend any type. This doesn't seam to match up with what I am seeing now and I am finding it difficult to find this documented.

Is there any truth to this or did my memory make it all up?

What are the rules relating to which types can be extended?

Are there any differences between C# 3 and 4?

Mamta D
  • 6,310
  • 3
  • 27
  • 41
Buh Buh
  • 7,443
  • 1
  • 34
  • 61

3 Answers3

6

Is there any truth to this?

No.

What are the rules relating to which types can be extended?

The rules for invocations are in section 7.6.5.2 of the C# 4 specification. The rules for declarations are in section 10.6.9.

To answer your specific question: unmanaged pointer types may not be extended.

Are there any differences between C# 3 and 4?

Yes. C# 4 adds additional rules for dealing with "dynamic". Extension methods are not resolved dynamically; if you have

dynamic d = 10;
d.MyIntExtension();

then the dynamic language runtime will not find the extension method on int. See

Will the dynamic keyword in C#4 support extension methods?

for more details.

Community
  • 1
  • 1
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
3

You made it up! As far as I'm aware there have been no changes to the rules between C#3 and C#4.

(And a cursory comparison of the relevant spec documents seems to confirm this.)

LukeH
  • 263,068
  • 57
  • 365
  • 409
3

Is there any truth to this or did my memory make it all up?

You made it up. Extensions methods have always been used on IEnumerable<T> .


Edit:

Here is the MSDN Link for Fx3.5 (C# 3) where the 2nd example is an extension for System.String, and String is not a primitive type.

Community
  • 1
  • 1
H H
  • 263,252
  • 30
  • 330
  • 514
  • 2
    But `IEnumerable` is an interface, so that doesn't answer his question :-) – Steven Jan 04 '11 at 12:07
  • @steven, yes, sloppy reading on my part. And most examples would be for interfaces. Thq question seems answered though. – H H Jan 04 '11 at 12:47
  • 1
    Thanks a lot. (I edited the question after a few seconds to add interfaces so that might have been my fault.) – Buh Buh Jan 04 '11 at 14:15