extension-methods

Detect target framework version at compile time

I have some code which makes use of Extension Methods, but compiles under .NET 2.0 using the compiler in VS2008. To facilitate this, I had to declare ExtensionAttribute: /// <summary> /// ExtensionAttribute is required to define extension methods under .NET 2.0 /// </summary> public sealed class ExtensionAttribute : Attribute { } Howe...

"asdf".Length > 0 vs. "asdf".Any()?

How is an arrays Length property identified, by an internal variable (i.e. m_Length) or it's gonna enumerate thru all the items of the array. The difference takes place if I want to check whether an array contains any elements. Dim asdf = { "a"c, "s"c, "d"c, "f"c } Dim any = asdf.Any() Dim any2 = asdf.Length > 0 (Also note that Any i...

First Time Calling Extension Methods is Slower Than Subsequent Calls

Hello, I have a class that modifies data via some extension methods. In order to debug performance, I have created some rough debug code to make multiple calls to the same methods using the same data a number of times. I am finding that it consistently takes a significantly longer time to do the calculations the first time through the...

C# Extension method for checking attributes

Hi All Sorry if this is a stupid noob question please be gentle with me I'm trying to learn... I want to test against the attribute methods of things like models and controllers. Mostly to make sure they have the right attrbute ie Required. But i'm also using this as an experiment with extension methods and Lambdas. What I'd like is a...

C# help with Extension Method - Converting collection to another type

I want to convert from public class Party { public string Type { get; set; } public string Name { get; set; } public string Status { get; set;} } and convert to public class Contact { public string Type { get; set; } public string Name { get; set; } public string Status { get; set;...

LINQ statement no longer works after being wrapped into an extension method

I had a need for a method that could take a collection of strings, and replace all occurrences of a specific string with another. For example, if I have a List<string> that looks like this: List<string> strings = new List<string> { "a", "b", "delete", "c", "d", "delete" }; and I want to replace "delete" with "", I would use this LINQ...

Why is the 'this' keyword required to call an extension method from within the extended class

I have created an extension method for an ASP.NET MVC ViewPage, e.g: public static class ViewExtensions { public static string Method<T>(this ViewPage<T> page) where T : class { return "something"; } } When calling this method from the ViewPage, I get the error "CS0103: The name 'Method' does not exist in the curre...

Generics and Extension Methods Together.

Hi I need to create an extension method to array class, but this extension method must be able to accept many data types, so it also must be generic. In the code bellow the extension method just accept byte data type. I want it to also accept ushort and uint for instance. I believe that the best way to do that is creating a generic typ...

Extension method for logging. A good idea?

What are, in your opinion, the pros/cons of the following extension method? static class Log { public static string AddToLog(this string input) { Console.WriteLine(input); return input; } public static string AddToLog(this string input, string format) { Console.WriteLine(format, input); ...

ASP.NET MVC 2/.NET 4/Razor - Can't use Any() extension method on a ViewModel member

I'm trying out the Razor ViewEngine from ASP.NET MVC 3 Preview 1 and I'm running into an issue trying to using the Any() extension method. Here's the code I use to set the property in the controller: ViewModel.Comparisons = DB.Comparisons.Where(c => c.UserID == this.UserID).ToArray(); Here's the code in the View where I try to use An...

Extension methods in C#: why does this work?

I'm a little confused as to why this doesn't give an error. I found this code deep inside of some outdated legacy software and was surprised to see it work. public static string CleanFileName(this string fileName) { return CleanFileName(fileName, 64); } public static string CleanFileName(this string fileName, int maxLength) { //so...

What is wrong here? I'm confused... ToJSON Extension Method

Given the following declaration: <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() Dim bytes ...

Advice With Repository/Service Layer Design Pattern

Hi Guys, Trying to make a really simple repository and service layer pattern here. (.NET 4, C#, LINQ, although this question is partially language-agnostic). Note: this is just R&D. My goal is to minimize the amount of method definitions in my service layer. Here's my Repository Contract: interface IFooRepository { IEnumerable<Foo...

C# generic function question

Hi, How to understand the following code? What does "this" mean in the generic function prototype? Thanks! public static class MyExtensions { public static MyStream<T> MySingle<T>(this T source) { return new MyStream<T>(source); } } ...

Comparison of Specification Pattern, Func<T,bool> Predicates and Pipes & Filters

Hi Guys, I'm doing some R&D work, and as such am exploring design patterns. I have recently been reading up on the Specification pattern and was referred to this great article. I was intrigued by the simplicity and cleanliness of the code, but i started to draw some comparisons to implementing the same cleanliness using other techniq...

c# Extension method

Hello, Im trying to test my extension method that converts a list of strings in a string comma separated: public static class Extensions { public static string ToCommaString<T>(this IList<T> input) { StringBuilder sb = new StringBuilder(); foreach (T value in input) { sb.Append(value); ...

MVC2 issues when edit an item on an textboxfor

Hello, i have this model on mvc: public class User { public string Name { get; set; } public IList<string>RelatedTags { get; set; } } And the following typed view (user) to edit an add a user (AddEdit.aspx view): <div> <%: Html.LabelFor(e => e.Name)%> <%: Html.TextBoxFor(e => e....

Is there a good reason why extension method classes can't be nested?

I've been using extension methods a lot recently to help make my code be more fluent, but I keep running into situations where I can't limit the exposure of the functionality I've created in the way I'd like. Say I have some code like this (completely made up example): var liveSet = allitems.Where(x => x.Status == Status.Live).Select(x...

Linq extension method, how to find child in collection recursive

Hi, I'm already familiar with Linq but have little understanding of extension methods I'm hoping someone can help me out. So I have this hierarchical collection pseudo code ie: class Product prop name prop type prop id prop List<Product> children And I have a list of products List products. Is there any way I can look for pr...

Is this extension method to force a string into an integer or default to 0 redundant?

I needed a one-liner to convert a string to an integer, and if the string is anything invalid, then just set it to zero. So I made the following extension method, but I can imagine there is a system method to do this in one line. Is there another way to do this in one line without creating an extension method? using System; namespace ...