extension-methods

In C#, what happens when you call an extension method on a null object?

那年仲夏 提交于 2019-11-26 18:12:26
Does the method get called with a null value or does it give a null reference exception? MyObject myObject = null; myObject.MyExtensionMethod(); // <-- is this a null reference exception? If this is the case I will never need to check my 'this' parameter for null? That will work fine (no exception). Extension methods don't use virtual calls (i.e. it uses the "call" il instruction, not "callvirt") so there is no null check unless you write it yourself in the extension method. This is actually useful in a few cases: public static bool IsNullOrEmpty(this string value) { return string

Impossible to use ref and out for first (“this”) parameter in Extension methods?

拜拜、爱过 提交于 2019-11-26 17:53:59
Why is it forbidden to call Extension Method with ref modifier? This one is possible: public static void Change(ref TestClass testClass, TestClass testClass2) { testClass = testClass2; } And this one not: public static void ChangeWithExtensionMethod(this ref TestClass testClass, TestClass testClass2) { testClass = testClass2; } But why? Jon Skeet You have to specify ref and out explicitly. How would you do this with an extension method ? Moreover, would you really want to? TestClass x = new TestClass(); (ref x).ChangeWithExtensionMethod(otherTestClass); // And now x has changed? Or would you

What causes “extension methods cannot be dynamically dispatched” here?

混江龙づ霸主 提交于 2019-11-26 17:49:46
问题 Compile Error 'System.Data.SqlClient.SqlConnection' has no applicable method named 'Query' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. Now, I know how to work around the problem, but I'm trying to get a better understanding of the error itself. I have class that I'm building to leverage Dapper. In the end I'm going to provide

Will the dynamic keyword in C#4 support extension methods?

故事扮演 提交于 2019-11-26 17:47:40
I'm listening to a talk about C#4 's dynamic keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods? public static class StrExtension { public static string twice(this string str) { return str + str; } } ... dynamic x = "Yo"; x.twice(); // will this work? Note: This question was asked before C#4 was shipped which is why it's phrased in the future tense. From the "New Features in C# 4" word doc : Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static

Enumeration extension methods

旧时模样 提交于 2019-11-26 17:39:53
问题 In vs2008, is it possible to write an extension methods which would apply to any enumeration. I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible? 回答1: Yes, just code against the base Enum type, e.g. public static void Something(this Enum e) { // code here } The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using Enum

Anonymous Types - Are there any distingushing characteristics?

别说谁变了你拦得住时间么 提交于 2019-11-26 17:38:14
Is there anything to use, to determine if a type is actually a anonymous type? For example an interface, etc? The goal is to create something like the following... //defined like... public static T Get<T>(this IAnonymous obj, string prop) { return (T)obj.GetType().GetProperty(prop).GetValue(obj, null); } //... //And then used like... var something = new { name = "John", age = 25 }; int age = something.Get<int>("age"); Or is that just the beauty of an anonymous type? Nothing to identify it self because it takes a new shape? Note - I realize that you can write an extension method for the object

What is the performance of the Last() extension method for List<T>?

冷暖自知 提交于 2019-11-26 17:33:23
问题 I really like Last() and would use it all the time for List<T> s. But since it seems to be defined for IEnumerable<T> , I guess it enumerates the enumeration first - this should be O(n) as opposed to O(1) for directly indexing the last element of a List<T> . Are the standard (Linq) extension methods aware of this? The STL in C++ is aware of this by virtue of a whole "inheritance tree" for iterators and whatnot. 回答1: I just used the Reference Source to look into the code for Last and it checks

Is it appropriate to extend Control to provide consistently safe Invoke/BeginInvoke functionality?

半腔热情 提交于 2019-11-26 17:26:41
In the course of my maintenance for an older application that badly violated the cross-thread update rules in winforms, I created the following extension method as a way to quickly fix illegal calls when I've discovered them: /// <summary> /// Execute a method on the control's owning thread. /// </summary> /// <param name="uiElement">The control that is being updated.</param> /// <param name="updater">The method that updates uiElement.</param> /// <param name="forceSynchronous">True to force synchronous execution of /// updater. False to allow asynchronous execution if the call is marshalled /

How to extend MVC3 Label and LabelFor HTML helpers?

时光总嘲笑我的痴心妄想 提交于 2019-11-26 17:01:26
问题 Html.Label and Html.LabelFor helper methods do not support the htmlAttributes parameter like most of the other helpers do. I would like to set the class however. Something like this: Html.LabelFor(model => model.Name, new { @class = "control-label" }) Is there an easy way of extending Label/LabelFor without resorting to copying and extending the ILSpy disasm output of those methods? 回答1: You can easily extend the label by creating your own LabelFor: Something like this should do what you need

Doesn't C# Extension Methods allow passing parameters by reference?

让人想犯罪 __ 提交于 2019-11-26 16:58:38
问题 Is it really impossible to create an extension method in C# where the instance is passed as a reference? Here’s a sample VB.NET console app: Imports System.Runtime.CompilerServices Module Module1 Sub Main() Dim workDays As Weekdays workDays.Add(Weekdays.Monday) workDays.Add(Weekdays.Tuesday) Console.WriteLine("Tuesday is a workday: {0}", _ CBool(workDays And Weekdays.Tuesday)) Console.ReadKey() End Sub End Module <Flags()> _ Public Enum Weekdays Monday = 1 Tuesday = 2 Wednesday = 4 Thursday =