Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods on a struct

Can you add extension methods to a struct?

like image 908
Ghyath Serhal Avatar asked Jan 11 '11 09:01

Ghyath Serhal


People also ask

Can structs have extension methods?

Yes, you can define an extension method on a struct/value type.

What are extension methods explain with an example?

Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions , they'll all be brought into scope by the using Extensions; directive.

Where do you put extension methods?

An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.


2 Answers

Yes, you can add extension methods on structs. As per the definition of extension method, you can easily achieve it. Below is example of extension method on int

namespace ExtensionMethods {     public static class IntExtensions      {         public static bool IsGreaterEqualThan(this int i, int value)         {             return i >= value;         }     } } 
like image 186
Pranay Rana Avatar answered Sep 20 '22 06:09

Pranay Rana


It is possible to add extension methods to structures, but there is an important caveat. Normal struct methods methods accept this as a ref parameter, but C# will not allow the definition of extension methods which do so. While struct methods which mutate this can be somewhat dangerous (since the compiler will allow struct methods to be invoked on read-only structures, but pass this by value), they can also at times be useful if one is careful to ensure that they are only used in appropriate contexts.

Incidentally, vb.net does allow extension methods to accept this as a ByRef parameter, whether it is a class, struct, or an unknown-category generic. This can be helpful in some cases where interfaces may be implemented by structures. For example, if one attempts to invoke on a variable of type List<string>.Enumerator an extension method which takes a this parameter of type IEnumerator<string>, or takes by value a this parameter of a generic constrained to IEnumerator<string>, and if the method tries to advance the enumerator, any advancement will be undone when the method returns. An extension method which takes a constrained generic by reference, however, (possible in vb.net) will behave as it should.

like image 24
supercat Avatar answered Sep 18 '22 06:09

supercat