Side Of Defining Extension Method?
Dec 16, 2011I've got a bunch of duplicate code that looks like this:If mValue is Nothing Return ""Return mValue.ToUpper
I defined the following extension method to reduce duplicate code:
[Code]...
I've got a bunch of duplicate code that looks like this:If mValue is Nothing Return ""Return mValue.ToUpper
I defined the following extension method to reduce duplicate code:
[Code]...
What is the side effects of defining a structure inside a class (name it X), and create a property inside that class of the type X?
View 1 RepliesWhy would I use an extension method instead of just creating non-extension sub or function?
For ex, I could have an extension function called IsNullOrEmptyOrAllSpaces on String, which does a check as its name implies. Or I can write a stand alone function that does the same thing. Other than having the extension show up in Intellisense, is there any advantage? Is a call to the extension quicker/more efficient than a call to a regular function?
I saw this post and I want to know if this is possible in VB. So like extension method, do extension properties exists in VB.Net? Here I've read they do, but cannot find any examples.
View 3 RepliesWrite an overload for every numeric type or if possible constrain a generic extension method to just numeric types.
View 2 RepliesExtension methods are useful for types that you don't own and can't/don't want to derive from and extend (e.g. reference types and interfaces). Obviously, interfaces should be kept as short and to-the-point as possible, so extension methods for interfaces are particularly useful (e.g. LINQ).For classes, especially classes that you own, they're still useful - but I'm wondering how you determine what should be an extension method or what should be a method in the class itself.Personally, every time I think about it, I keep going round in circles with the following thoughts:If it's useful enough, it should be in the class.It's not part of the core responsibility of the class, it should be an extension method - but if it's useful enough, surely it should be the responsibility of the class...
View 3 RepliesIs there a down side to using the Compute method, like this, [code] or would it be better to add the query to my datasource?
View 3 RepliesI know how to add extension method Like (Date.Now.MyExtensionFunction()),But I can NOT find how to add such methods and functions in class (not in module) with vb.net
View 3 RepliesI am trying to write extension methods in VB.NET
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
[code]....
But I am getting this error.Class 'System.Web.UI.WebControls.ListItem' cannot be indexed because it has no default property
What could be wrong?I am calling the code like this.
ddlSalesmanager.Items.FindByText(survey, StringComparison.CurrentCultureIgnoreCase)
P.S: I ported this wonderful code from C# to VB
I converted some code from c# for a VB.net project I have an object declared as this :
<Serializable()> _
Public Class oUserApplication
Public ApplicationID As Integer = 0
Public ApplicationRoleID As Integer = 0
[code]....
I ran into a strange issue over the weekend while I was working on an asp.net mvc project in vb.net. I created an extension method to convert an integer to the corresponding month it is associated with. I tested the extension method in a console application so I know it is working.
In my asp.net mvc project I have a view and want to call the extension method but I get an error that the extension method is not recognized. I imported the namespace it was contained in and still couldn't shake the error.
Extension Method:
Imports System.Runtime.CompilerServices
Module SiteExtensions
<Extension()> _
[Code].....
I want to implement an extension method in VB.NET that will clone an object of type T.Say, I want
Dim cust1 as New Customer() //...
Dim cust2 as New Customer() //...
cust2 = cust1.Clone()
[code]....
I created a module to add some Extension Methods to a Class. This Class inherits from another parent Class. In the code of my Extension Methods, I would like to refer to the base Class using MyBase. This doesn't seems to be allowed (Error message : "'MyBase' is not valid within a Module.")
[Code]...
I am starting to play with extension methods and i came across with this problem:In the next scenario i get a: "extension method has a type constraint that can never be satisfied"
Public Interface IKeyedObject(Of TKey As IEquatable(Of TKey))
ReadOnly Property InstanceKey() As TKey
End Interface
[Code]...
I'm trying to create an extension method that returns an IEqualityComparer based on a lambda function. Heres the extension method:
<Extension()>
Public Function Comparer(Of T)(Func As Func(Of T, T, Boolean)) As IEqualityComparer(Of T)
Return New GenericComparer(Of T)(Func)
End Function
[Code]...
I have a Direction Enum:
Public Enum Direction
Left
Right
Top
Bottom
End Enum
And Sometimes I need to get the inverse, so it seems nice to write:
SomeDirection.Inverse()
But I can't put a method on an enum! However, I can add an Extension Method (VS2008+) to it.
In VB, Extension Methods must be inside Modules. I really don't like modules that much, and I'm trying to write a (moderately) simple class that I can share in a single file to be plugged into other projects.
Modules can only reside in the file/namespace level so I have one in the bottom of the file now:
Public Class MyClass
'...'
End Class
[Code]....
It works, and "if it ain't broke, don't fix it", but I'd love to know if I'm doing it wrong and there's a better way with less boilerplate. Maybe in .NET 4?
Finally, I know I could write a structure that behaves like an enum, but that seems even more backwards.
I've created a MyFunc extension (in Module Extensions) for all the base types as well as generic arrays, ICollection(Of T) and Dictionary(Of String,T):
Function MyFunc(Of T)(a() As T) As String
Function MyFunc(Of T)(collection As ICollection(Of T)) As String
Function MyFunc(Of T)(dict As Dictionary(Of String,T)) As String
[code].....
how do we access MyBase from an extension method?
i'm trying to extend a Sub called PassDown that would call the form's Base's OnPaint method
<Runtime.CompilerServices.Extension()> Public Sub PassDown(ByVal form_instance As Windows.Forms.Form, ByVal e As EventArgs)
MyBase.OnPaint(e)
but of course, mybase couldn't be accessed this way so is there an alternative?
Can I access values in application settings of web.config in extension method?I have the below code but it is not working:
<Extension()> _
Public Function DocCountExt(ByVal value As Collection) As Integer
Dim maxOffSet As Integer = Integer.Parse(ConfigurationManager.AppSettings(APP_SETTINGS_OFFSET))
return maxOffSet
End Function
The above code does not work.
i want to extend the integer class to a method that increments current integer value by 2. I create a console application and a second module which contains the extension method.
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
[code]....
and everything works fine. The extension method module can be imported to any other project (Project-->add existing item --> select the vb file that contains the extension method module) and works fine too. But the code is accessible to other users. Is there a method to convert the extension method module to a dll and adding it to other projects as a reference. I tried to do it with creating a class project and pasting the code of the extension method module and compile the dll and then added it as reference to another project and imported the class with the keyword imports, but it didn't work.
I wanna create extension method for IEnumerable(Of FileSystemInfo). However, compiler says "'Sort' is not a member of'System.Collections. Generic. IEnumerable(Of System.IO.FileSystemInfo)". What is strange is that IntelliSense shows this method. Where's error? [code]
View 1 RepliesIn our .aspx pages, we've got lots of this code:<%= CType(GetLocalResourceObject("key"), String)) %>I'd like to add an extension method that I can use in our .aspx views that allows me to do this:<%= GetLocalResourceString("key") %>The code isn't working, though:Imports System.Runtime.CompilerServices
View 1 RepliesI 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
In VB.Net you can easily get the text value of the first child element of an XElement like so:Dim sChildValue = xeParent.<MyChild>.Value()Of course that syntax is not supported in C#, but it produces the same IEnumerable(Of XElement) result as the Elements() method. So we can rewrite the above like so:
Dim sChildValue = xeParent.Elements("MyChild").Value()This Value() extension method is handy because often you are working with small XML documents and you just want the first node that matches. (One thing that annoys me about this method is that it seems to return Nothing/null if the IEnumerable list is empty due to the specified element not being found. To work around this I have created my own ValueOrBlank() method that returns an empty string in that situation instead.)
My problem is that I can't do the same thing in C#:var sChildValue = xeParent.Elements("MyChild").Value(); // won't compile, can't find Value() method
I checked my references/imports and they match the VB.Net project where the same call works. Fortunately I am able to use my custom ValueOrBlank() extension method to accomplish the same thing. But I'm curious as to what's missing in my C# project. I tried right-clicking on the Value() method call in Visual Studio and clicking "Go To Definition" to see if the Object Browser could tell me where the extension method is kept, but it just shows the System.String class. Does that mean this is one of those sneaky VB.Net-only features that the compiler itself supports, like the XML Axis < MyChild > syntax?
I am wondering whether I can use DataContractJsonSerializer to serialize a Structure type, or does it have to be a reference/Class type? I have the following code:
<Extension()> Public Function ToJSON(ByVal target As Object) As String
Dim serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(target.GetType)
Using ms As MemoryStream = New MemoryStream()
serializer.WriteObject(ms, target)
ms.Flush()
[Code]...
And yet if I call it on a Structure type, such as a KeyValuePair(Of T1, T2), I get the following error:
Public member 'ToJSON' on type 'KeyValuePair(Of String,Object)' not found.
Is there anyway to add an overload "extension method" to a method that already has one or more extension methods?For example theString.Contains method has two extension methods totalling 3 separate versions.Is there anyway to add an extra extension method also called "Contains" ?By the way I have tried it but the IDE does not seem to recognise additional EXTENSION methods where a method already hasone or more extension methods.Is there anyway around this restriction?In other words I would like to be able to change the Extension method below from"Contain" to "Contains" but it seems it is not recognised.
Option Strict On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
[code].....
From previous experience I had been under the impression that it's perfectly legal (though perhaps not advisable) to call extension methods on a null instance. So in C#, this code compiles and runs:
// code in static class
static bool IsNull(this object obj) {
return obj == null;
}
[code]....
The debugger stops right there, as if I'd called an instance method. Am I doing something wrong (e.g., is there some subtle difference in the way I defined the extension method between C# and VB.NET)? Is it actually not legal to call an extension method on a null instance in VB.NET, though it's legal in C#?
It seems that my library of extension methods that was written in VB.NET has problems.I have 2 overloaded extension methods Crop().When i reference the lib from a VB.NET project i see them. If reference it from a C# project i can't see them.
View 3 RepliesCan I make an Extension method for all the subclasses of System.Object (everything)?
Example:
<Extension>
Public Function MyExtension(value As Object) As Object
Return value
End Function
The above functions won't work for object instance:UPDATE The problem seems to occur only in VB, where members of object are looked-up by reflection (late-bound).UPDATE AFTER ANSWERED.FYI, as vb has an advantage that C# lacks that is, members of imported Modules are imported to the global scope so you can still use this functions without their wrapper:Dim myObj2 = MyExtension(myObj1)
After looking at this thread.>>
How to randomize the alphabet I have decided to make it into an extension method for a String and a List.
Note: Please see the following post if you are still using VB.Net 2002, 2003 or 2005
this code is for use with 2008 and later versions of VB.Net
String.Mix and also List.Mix I was trying to write a generic extension method for every Enumerable(Of T)
I settled on just doing it for a STRING
[Code]...