Can you add extension methods to a struct?
Yes, you can define an extension method on a struct/value type.
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.
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.
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; } } }
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.
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