Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create extension to shared method

Tags:

.net

vb.net

I like to create an extension method to Image.FromStream

Public Shared Function FromStream(ByVal stream As System.IO.Stream) As System.Drawing.Image

With possibility to cancel processing like

Public Shared Function FromStream(ByVal stream As System.IO.Stream, ByVal CloseTask As ManualResetEvent) As System.Drawing.Image

Is it possible?

like image 594
walter Avatar asked Jul 24 '11 08:07

walter


People also ask

How do you declare an extension method?

An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.

How do you use an extension method?

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. string s = "Hello Extension Methods"; int i = s. WordCount(); You invoke the extension method in your code with instance method syntax.

How do you extend a method in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

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

No, you can only add extension methods which appear to add instance methods to a type - you can't make it look like you've added new shared methods to a type.

like image 78
Jon Skeet Avatar answered Oct 06 '22 06:10

Jon Skeet


I have a somewhat dodgy way I do shared extensions.

I use the Extensions class to resolve the conflict in having the same signature for my functions

Module Main
    Public Class Extensions
        Public Class [Boolean]
            Public Shared Function TryParse(ByVal strValue As String, ByRef blnResult As Boolean) As Boolean
                If Not Object.Equals(strValue, Nothing) Then
                    If strValue = "Y" Then
                        blnResult = True
                        Return True
                    End If

                    If strValue = "N" Then
                        blnResult = False
                        Return True
                    End If
                End If

                Return Boolean.TryParse(strValue, blnResult)
            End Function
        End Class
    End Class

End Module
like image 21
NMGod Avatar answered Oct 06 '22 05:10

NMGod