Extension methods on a struct

why we use extension method in c#
string extension method c#
c# extension methods
extension method with parameters in c#
c# extension properties
c# extension method not found
c# static extension method
linq extension methods

Can you add extension methods to a struct?

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;

Extension Methods, I then add in my method, write the implicit conversions and then put in all the other Datetime methods etc. This would be a pain to code (Being  Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

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.

Champion "ref extension methods on structs" (C# 7.2) · Issue #186 , , this is comparable to a category in Objective-C. For more information, see Extension Methods. Implicitly Typed Local Variables. Within a class or struct method, you can use implicit typing to instruct the compiler to determine the correct type at compile time. For more information, see Implicitly Typed Local Variables. C# Language Specification. For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

For future Googlers (and Bingers), here's some code to extend a struct. This example turns the value into a double type.

public static class ExtensionMethods {

   public static double ToDouble<T>(this T value) where T : struct {
      return Convert.ToDouble(value);

After this you can use ToDouble() like you use ToString(). Be careful on conversion items like overflows.

Extending a struct. Using helper classes rather than composition , to existing types without even creating a new derived type, recompiling, or modifying the original type. Extension methods can let you use helper functions with the syntax of method calls, which can be nice for Intellisense or when a function call looks better in infix form. This is pure syntax sugar; semantically there's not much of a difference between extension methods and regular static methods.

Yes, you can define an extension method on a struct/value type. However, they do not have the same behavior as extension methods on reference types.

For example, the GetA() extension method in the following C# code receives a copy of the struct, not a reference to the struct. This means that a C# extension method on a struct can't modify the original struct contents.

public static class TestStructExtensionMethods {
    public struct FooStruct {
        public int a;
    public static int GetA(this FooStruct st) {
        return st.a;

In order to modify the struct contents, the struct paramater needs to be declared as "ref". However, "this ref" is not allowed in C#. The best we can do is a static non-extension method like:

// this works, but is inefficient, because it copies the whole FooStruct
// just to return a
public static int GetA(ref FooStruct st) {
    return st.a;

In VB.NET, you can create this as a ByRef struct extension method, so it could modify the original struct:

' This is efficient, because it is handed a reference to the struct
<Extension()> _ 
Public Sub GetA(ByRef [me] As FooStruct) As Integer
    Return [me].a
End Sub

' It is possible to change the struct fields, because we have a ref
<Extension()> _ 
Public Sub SetA(ByRef [me] As FooStruct, newval As Integer) 
    [me].a = newval
End Sub

How do I subclass a struct in Swift?, Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface. Extension methods can  Structs are mainly useful to hold small data values. A structure can be defined using the struct operator. It can contain parameterized constructor, static constructor, constants, fields, methods, properties, indexers, operators, events and nested types. Structure Declaration. A structure is declared using struct keyword with public or internal modifier.

Extension Methods in C#, Write a static class that extends struct Double with the two extension methods Sqrt and Square . Afterwards, rewrite the method DistanceTo such that it makes  gafter changed the title Champion "ref extension methods on structs" Champion "ref extension methods on structs" (C# 7.2) Sep 23, 2017 zpodlovics mentioned this issue Nov 4, 2017 Tracking corner edge cases of F# performance / Usage of new CLR features #3476

C# Extension Methods, With extension methods, we can extend structs, interfaces, inherited classes, and base classes. The ability to extend interfaces is particularly  An extension can extend an existing type to make it adopt one or more protocols. To add protocol conformance, you write the protocol names the same way as you write them for a class or structure: extension SomeType: SomeProtocol, AnotherProtocol {. // implementation of protocol requirements goes here.

C# Extension Method, Extension Methods are a language feature that allow you to add methods to an existing type (class, struct, interface, etc). In a language like C#, an Extension  The struct data type can contain other data types so is used for mixed-data-type records such as a hard-drive directory entry (file length, name, extension, physical address, etc.), or other mixed-type records (name, address, telephone, balance, etc.).

  • Have you tried adding an extension method on a struct? Note that you shouldn't delete questions when you find the answer to them, others might wonder about the same thing. And yes, you can declare them, but changing things in the struct won't work like you expect it to, unless you expect it to not work.
  • Yeah i tried but it did not work.
  • Thank you it worked, my fault
  • I think this question might be imprecise enough to capture the subtlety of answers, for struct extension methods really are not like object extension methods in that they receive a copy of the struct not a reference to the struct. A better way to phrase this might be "What does it mean to define an extension method on a struct?"
  • Be careful with this though, as the struct is passed into the extension method BY VALUE (as structs are want to do). Hence, any modifications you make to the struct in the extension method will be lost -- unless you return the struct of course (and then do something with that passed back struct, such as reassign it to itself). There is no way to do an extension method on a struct and have it be passed in by reference (in C#).
  • It seems like that I cannot extend System.Drawing.Rectangle which is also a struct,and decorated with Serializable and ComVisible and TypeConverter.
  • BrainSlug83 C# 7.2+ now supports refs in struct extension methods.
  • So what might be an example of using one in C#? public static Rect CreateRectFromPercents(this Rect rect) for example does not work.
  • @MichaelTaylor3D: What is Rect? Do you mean System.Drawing.Rectangle or some custom type?
  • its a struct that is part of my api im using. I was just using it as an example. The api blocks me from modifying it directly so I was hoping to use an extension method. Ive read that its possible for structs but i havnt seen an example yet. Your explanation is the closest i can find.