Extension method - having to use this keyword? - c#

I have added an extension method to the ASP.NET System.Web.UI.Page.
Every page in my application inherits from this class.
I cannot just access the extension method, however. I must type this.MyMethod(); instead of just being able to use MyMethod(). I thought that methods/attributes of this were inherently in the default scope. What am I not understanding? Or is this a nuance of extension methods?

I thought that methods/attributes of
this were inherently in the default
scope.
They are. But extension methods are not methods of this in the default scope; they are static methods accessible via syntactic sugar provided as a courtesy by the compiler.
I believe you already know this, but just to clarify: if ExtensionMethod is an extension method of the class whose scope you're currently in, typing this:
this.ExtensionMethod();
...is the same as:
SomeStaticClass.ExtensionMethod(this);
this needs to be passed as a parameter to ExtensionMethod. The first way above, the compiler simply does this for you.
Naturally, they could have implemented things differently so that the compiler "brings in" extension methods as well as class members into the default scope; they just simply chose not to. Personally, I like that; but I guess it's a subjective matter. Anyway, if you dislike having to type this, it's only a small annoyance, right?

is this a nuance of extension methods?
Yes, it is. (As others have explained.)
If you want to use the method without any qualification, then you could just make a class that inherits from Page and includes your method (minus the first paramater, of course). Then make each page in your application inherit from your new custom page.

In order to use extension method you should declare:
using Namespace.Where.Extension.Method.Is.Located
And don't forget that class that holds extension method should be static.

Related

how to hide method overloads from intellisense and main class code file when project is part of VS2013 solution?

I have too many method overloads for each method and I'm thinking how to make MyClass more easily understandable/usable to other developers. My ideas:
1.
make it partial class and new file name MyClassOldMethods.cs with all methods marked
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
this does not work, cause project is part of solution.
2.
Make old method overload as extension methods in other file in new static class. But I can't hide them from intellisense or can I?
Lots of existing code exist so the solution must be backward compatible. I have a feeling that this is wrong in a 1st place, but can it be done?
Edit:
SO wants me to explain that How to hide public methods from intellisense is not a duplicate. it does not answer the question. i read it before posting. The answers clearly state that EditorBrowsableState does not hide anything in same solution and it has nothing to do with partitioning obsolete but somewhere used overloads. I want to know is it wrong to move instance mthods to extension methods.
Extension methods will be hidden from Intellisense if they are in a separate namespace which is defined among the using namespaces. If you need an extension method you can always add using some.namespace.with.extensions and it will be available again. This approach should be used wisely and extension methods should be used where they are appropriate. ReSharper doesn't use this rule and shows all possible extension methods from referenced libraries.
If a class implements many interfaces and there is no need to show all implemented methods, you can use the explicit implementation, for example:
public class SomeClass : SomeInterface
{
void SomeInterface.SomeInterfaceMethod()
{
// ... some code ...
}
}
When you check all methods of the class, SomeInterfaceMethod will not be shown unless the class is cast to the SomeInterface type.

In FluentAssertions, why is Should a method instead of a property?

In FluentAssertions, you can make various claims in various formats.
x.Should().BeEquivalentTo(y);
x.ShouldBeEquivalentTo(y);
are both valid assertions.
Why is Should a method and not a property? I haven't seen any examples in which Should takes a parameter, so it seems to me like it could have easily been a property.
You can also assert that
x.Should().NotBeNull().And.BeEquivalentTo(y);
Here, And is a property instead of a method. Shouldn't And and Should each be the same type of element (methods/properties)?
TL;DR
Was there a valid reason behind the design choice to make Should a method in FluentAssertions instead of a property?
Should() is an extension method being added onto the class of x. You can only add extension methods -- C# doesn't have extension properties.
And is a property on whatever class NotBeNull() returns. There we have control over the class, and can add real properties to it.
Should() is a method because of the limitations of the C# language. It's an extension method; a method that is defined in the FluentAssertions library to be available to call on any type (hence x.Should()) - even though the original code for the class doesn't implement the method.
You can't implement extension properties, so Should has to be a method.
That method returns an object defined within FluentAssertions, as does NotBeNull(), and so these objects can include properties where it's relevant/useful/meaningful to do so.
In short: the valid reason is that it's the only choice available.

C# generic function question

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);
}
}
this in this context means it is an extension method so you can either use it the "normal" way:
MyExtensions.MySingle(someSource)
or this (sometimes nicer) way:
someSource.MySingle()
This is only possible when the method is static and is in a static class. Also, it have nothing to do with the generic aspect of the method - you can make extension methods without generics aspects and you still have the this in front of the parameter.
Extension methods, as the name suggest, is used for extending already existing classes with methods if you don't have access to the source or if you want it to be used over a broad set of classes. It is important to note, that you don't get access to private and protected methods etc., like when you derive from the class, when you make a extension method on a type.
Also, for a in-depth explanation:
Extension Methods (C# Programming Guide)
That it is an extension method, that becomes a valid method of all objects of type T.
It has nothing to do with generics.
MySingle<T> is defined as an extension method (MSDN).
This means that in usage you can call it like this:
MyStream<string> stringStream = "a string".MySingle();
This is identical to calling it in the "standard" way:
MyExtensions.MySingle("a string");
When you call it the first way (as an extension method), the item on which it is called is passed as the first parameter. The type of the first parameter therefore defines the type on which the extension method can be called, but since you have an open generic type, it can be called on any object.
To define an extension method, the containing class and the method itself must be declared static.
Extension methods were added in C# 3.0 and VB 9.0.
This is an extension method, this is the instance that the method is applied to.
Yes it is an extention method but as far as i understand he is also asking what does it mean using a T (generic type definition) with "this" keyword in the method signature.
It means that the extention method will be valid method for all objects of every class and struct types in your project.
This indicates it is an extension method. The type being extended is 'T'.
All instances of 'T' will have method MySingle .

What is an Extension Class?

My teacher asked us to investigate what an Extension Class was but I can't seem to find anything on MSDN or Google. Any help?
There's no such thing as "extension class" in formal C# terminology. It might mean a class defining extension methods (which is not anything special, it's just a simple static class.)
Your teacher may also be talking about partial classes...
Technically an "extension class" is not anything. In the vernacular it could be used by someone to refer to a class that is designed to store extension methods. Extension methods are methods used to look like instance methods of a class, but which are truly static methods in a static class that are provided to enhance and encapsulate certain functionality. They are especially useful when you are trying to extend certain functionality on a type that you cannot modify directly and add a method to. Additionally, they are often used with generic types (especially within the .net 3.5 framework) to extend functionality using the methods provided by a specific interface.
A class that has extension methods.
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 a special kind of static method,
but they are called as if they were
instance methods on the extended type.
For client code written in C# and
Visual Basic, there is no apparent
difference between calling an
extension method and the methods that
are actually defined in a type.
An Extension class in C# could simply be a child class( inheriting and adding more functionality to the base type or interface) or a static class.
I dont know extension class is there .But extension method is there .
Try this
Extension Method
I know this question is a little bit older but one thing that came to my mind when I read this question is the refactoring book by Martin fowler. In Chapter 7 Moving Features Between Objects, he describes a refactoring called Introduce Local Extension . There he talks about creation an extension class which is nothing more or less than a subclass or a wrapper around an object. The purpose of this extension class is to extend the functionality of an existing class like Date (The Java class Date not the DateTime class of .Net which is in fact sealed).
Some of the other answers here refered to the extension Method which seems to be another way of using the refactoring Introduce foreign Method. I am not sure about this, so I maybe mistaken here.
I think the book was written in 1999 with most examples in Java so maybe this doesn't relate so much to .Net but I guess the concept is universal.
The closest thing to an Extension Class that I can come up with is for example Microsoft's ExceptionExtensions class.
https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ff654014(v=pandp.10)
If you create your own method in a class with that name, it becomes accessible from the Exception object.
public static class ExceptionExtensions
{
public static String myMethod(this Exception ex)
{
return ("Hi!");
}
}
Access it this way:
catch(Exception ex)
{
String message = ex.myMethod();
}

When do you use extension methods, ext. methods vs. inheritance?

We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
Also, I would appreciate if you also list all dark prerequisites for using them.
Times to use extension methods:
when you don't control the types being extended
where you don't want to force the implementor to provide code that can be done using the existing methods
For an example of the second point; you might have an extension method on IList<T> (for example, Sort) that can be written entirely using the existing IList<T> members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide much more functionality without breaking anything.
Times to not use extension methods:
when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
when you need access to private/protected members
Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:
Extension methods cannot be used to override existing methods
An extension method with the same name and signature as an instance method will not be called
The concept of extension methods cannot be applied to fields, properties or events
Use extension methods sparingly....overuse can be a bad thing!
This link http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/26/c-extension-methods---to-extend-or-not-to-extend.aspx provides good guidance on when to use Extension methods and when not.
To quote from this article:
A good extension method should:
- Apply to any possible instance of the type it extends.
- Simplify logic and improve readability/maintainability.
- Apply to the most specific type or interface applicable.
- Be isolated in a namespace so that it does not pollute IntelliSense.
I use extension methods when it makes sense. If you control a class and its code, you usually don't need extension methods.
If you don't, an extension method might be useful.
One place I frequently use extension methods is for [Flags] enumerations. When you have a flag-based enumeration, there's a rather large expression that's necessary to determine whether or not an enumeration value has a particular flag set. And so I build the following extension method whenever I build a [Flags] enumeration:
[Flags]
public enum MyEnum
{
FlagA,
FlagB,
// etc.
}
public static class MyEnumExt
{
public static bool HasFlags(this MyEnum item, MyEnum query)
{
return ((item & query) == query);
}
}
That way my code looks like:
MyEnum flags = MyEnum.FlagA;
if(flags.HasFlags(MyEnum.FlagA))
{
// handle FlagA
}
Rather than:
MyEnum flags = MyEnum.FlagA;
if((flags & MyEnum.FlagA) == MyEnum.FlagA)
{
// handle FlagA
}
Honestly, I would say it is easier to explain when it is NOT a good idea than when it is a good idea.
I think, the main benefit to extension methods is that they may increase the adoption of your method. This is because the user will not have to instantiate an instance of another class in order to use your method and intellisense will advertise your method when a developer is looking for methods for the class you are extending. This could be important if you are trying to get other developers to follow a new standard in your company.
When contemplating whether or not to create an extension method, remember the SOLID principles.
Single Responsibility:
- You are almost always at least bending the single responsibility principle with an extension method because you are tacking on to something that is already a class (that you either don't have control over or are too afraid to touch).
Open/Close Principle:
- Extension methods cannot be overridden, which means your method may not be adequately "open for extension".
Liskov substitution principle:
- If you have any sort of inheritance structure you will not be able to use the extension methods on the sub types.
Interface segregation principle:
- Although you can "extend" an interface, you have to provide a concrete implementation for that extension. So you can not program towards an interface >that can be implemented differently in a different context (eg Unit Test)
Dependency inversion principle:
- If your code has any dependencies, how are you going to expose those dependencies for factories and unit tests (dependency inversion principle)?
Finally, extension methods are just static methods wearing a new dress. So all of the difficulties with static methods (such as thread safety, garbage collection, etc) come along with extension methods when you implement them.
So, I would think long and hard about writing a method as an extension and reconsider using a factory and a basic helper class instead.
If you do write an extension method, please make it very simple. Try to avoid having any dependencies (or pass all of your dependencies in as parameters). And be careful for how you manage memory and lock resources in a multi-threaded environment.
What are extension methods?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Important points for the use of extension methods:
1.An extension method must be defined in a top-level static class.
2.An extension method with the same name and signature as an instance method will not be called.
3.Extension methods cannot be used to override existing methods.
4.The concept of extension methods cannot be applied to fields, properties or events.
5.Overuse of extension methods is not a good style of programming.
Use inheritance when "Is-A" relationship makes sense. Inheritance create unwanted dependencies between the classes.
I use extension method when I feel "what good it would have been if XYZ class had ABC method".
I remember the best exammple when I used extension method when I needed to break collection into chunks.
Here is the details.
https://www.codingcrest.com/extension-method-in-c/

Categories