When to use this keyword as function argument [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does “this” mean in a static method declaration?
i go through a code snippet and found this keyword is used as function argument.
the code snippet is like
public static void AddCell(this Table table, object cell)
why AddCell has this keyword they can write likeAddCell(Table table, object cell)
please explain the situation when to use this keyword as function argument with small code sample as a result i can better understand. thanks.

Basically what is being defined in your example is an extension method. In a static method, if you define the first argument using the this keyword you are allowing the method to be called on instance objects of the type defined on the first argument.
In the example you stated you would be able to do something like this:
Table someTableInstance; /// must be instanciated somehow;
someTableInstance.AddCell(cell); // Call the AddCell method as if it was an instance method.
Hope it helps,
Regards,
Bruno

This syntax is used for extension methods.
These look a bit odd when you first see them written, but they are fabulous things - most of Linq is written as extension methods.
Here's a good intro tutorial - http://csharp.net-tutorials.com/csharp-3.0/extension-methods/ - which includes the example:
public static class MyExtensionMethods
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
which enables you to call:
"fred".IsNumeric()

this is the keyword for creating extension methods.
This way, while I have not changed the implementation of Table, I can call method AddCell on a member of Table.
MSDN:
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.

It's a declaring an extension method. The point is that as well as
MyStaticClass.AddCell(table, cell);
you can now just call
table.AddCell(cell);
assuming MyStaticClass is in the current namespace or namespaces you've usinged.

The 'this' keyword is used to create an extension method. For instance, if you are using a library class that you want to add a method to without inheriting a new derived type, you can create a static extension method. It is syntactical-sugar that places a regular static method onto an already known type.
For example:
public static int ToNumber( this string numberString )
{
int convertedInt = 0;
// logic goes here to convert to an int
return convertedInt;
}
Can be called like this:
string myNumberString = "5";
int num = myNumberString.ToNumber();
You didn't have to create an inherited class to do this but it reads cleanly.

Related

What does 'this' keyword mean in a method parameter? [duplicate]

This question already has answers here:
What are Extension Methods?
(13 answers)
Closed 10 years ago.
namespace System.Web.Mvc.Html
{
// Summary:
// Represents support for HTML in an application.
public static class FormExtensions
{
public static MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName);
...
}
}
I have noticed that 'this' object in front of the first parameter in BeginForm method doesn't seem to be accepted as a parameter. Looks like in real BeginForm methods functions as:
BeginForm(string actionName, string controllerName);
omitting the first parameter. But it actually receives that first parameter somehow in a hidden way.
Can you please explain me how this structure works. I actually exploring MVC 4 internet Sample.
Thank you.
This is how extension methods works in C#. The Extension Methods feature allowing you to extend existing types with custom methods.
The this [TypeName] keyword in the context of method's parameters is the type that you want to extend with your custom methods, the this is used as a prefix, in your case, HtmlHelper is the type to extend and BeginForm is the method which should extend it.
Take a look at this simple extention method for the string type:
public static bool BiggerThan(this string theString, int minChars)
{
return (theString.Length > minChars);
}
You can easily use it on string object:
var isBigger = "my string is bigger than 20 chars?".BiggerThan(20);
References:
Well-documented reference would be: How to: Implement and Call a
Custom Extension Method (C# Programming Guide)
More particular reference about Extention Methods in ASP.NET MVC would be:
How To Create Custom MVC Extension Methods
Extension Methods:
A "bolt on" way to extend an existing type. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. Or you might want to have the Show() Hide() functionality in ASP.net WebForms for controls.
For Example:
public static class MyExtensionMethods
{
public static void Show(this Control subject)
{
subject.Visible = true;
}
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
Edit:
For futher information you can see the MSDN documentation at: http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx which was kindly linked by #aush.
I enjoyed reading "C# In Depth" regarding Extension Methods. There is an excerpt available here:
http://my.safaribooksonline.com/book/programming/csharp/9781935182474/extension-methods/ch10lev1sec3
You can of course buy the book online or you can just do some research into how it all works under the hood using Google.

object - How top most base class got Method. [Extension Method]

Yesterday i gone through some article about EventAggregator, there some shot of code written like this,
(Message.Text as object).PublishEvent(PublishEventNames.MessageTextChanged);
public static class ExtensionServices
{
//Supplying event broking mechanizm to each object in the application.
public static void PublishEvent<TEventsubject>(this TEventsubject eventArgs, string eventTopic)
{
ServicesFactory.EventService.GetEvent<GenericEvent<TEventsubject>>()
.Publish(new EventParameters<TEventsubject> { Topic = eventTopic, Value = eventArgs });
}
}
My question is, how the object got the method "PublishEvent". Is my OOP understanding is wrong?
It was implemented as an Extension Method on the object class.
For example, this extension method (from the linked article):
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
Is defined on the String class (by using the this String syntax and a static method on a static class) .
In the project that this is defined in String now has a WordCount method (so long as it is also in the correct namespace).
Extension methods are not actually part of the object that you appear to call the method on. Extension methods are in an additional lookup scope that the compiler looks in after looking for the method in the scope of the object itself.
So, for a method call like obj.MyExtension(), the compiler will look for "MyExtension" in the members of the type of the obj variable. It won't find any matches, because "MyExtension" isn't defined in the object's type. The compiler then looks for extension methods named "MyExtension" that are available in the current scope (because of using clauses) that have a this parameter whose type matches the type of the obj instance variable. If a match is found, then the compiler generates code to make a static method call that other method, passing obj in the this parameter.
I believe the extension methods scope is a "last chance" lookup - if the compiler can't find "MyExtension" in the available extensions, the next step is to fail with a compile error.
The tricky thing with extension methods is they're only accessible when you have added the appropriate using clause to the current source file and added a reference to the appropriate assembly that implements the extensions to bring them into scope.
Intellisense doesn't help you resolve these names by adding the appropriate using clause for you. As a user, you get used to calling a particular method on a particular type of object, and you mentally associate that method as being part of that type. When you're fleshing out a new source file it's very common to write calls to that method as you normally would and get "not found" compiler errors because you forgot to reference the namespace / assembly containing the extension method definition(s) to your source file.
The this part of this TEventsubject eventArgs determines that this is an Extension method.
It is only syntactic sugar to be able to write
TEventsubject eventArgs;
eventArgs.PublishEvent("topic");
Instead of
TEventsubject eventArgs;
ExtensionServices.PublishEvent(eventArgs, "topic");
PublishEvent is an extension method.
You can tell by the definition of the method, which includes the this keyword in the arguments list.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
Extension methods are very useful syntactically; but they should be used judiciously:
1) They can clutter Intellisense if too many extensions are added for non-specific types (such as an object).
2) They should be used to augment class/interface inheritance, not replace it. IMO, If a method is shared across completely unrelated types, then it is a good candidate for an extension method. But if it is shared across related types, then it is a better candidate for a method in a base class.

extension method to extend static class [duplicate]

This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 8 years ago.
I am wondering if I can use extension method or other techniques to extend static class like
System.Net.Mime.MediaTypeNames.Image, it has fewer type than I need.
No, extension methods can only be used to add instance methods, not static methods (or even properties). Extension methods are really just syntactic sugar around static methods. For instance, when you use an extension method such as Count():
var list = GetList();
var size = list.Count();
This is actually compiled to:
var list = GetList();
var size = Enumerable.Count(list);
You can't add additional static methods to an existing class using extension methods.
No, this is not yet possible in C#, though hopefully it will become so at some point. And you can't subclass a static class and add new methods that way, since static classes must derive from object. One thing you can do though, which produces a pretty similar effect in your code, is simply declare another static class that you will use instead when you want your extension methods. For example:
public static class MessageBox2
{
public static DialogResult ShowError(string Caption, string Message, params object[] OptionalFormatArgs)
{
return MessageBox.Show(string.Format(Message, OptionalFormatArgs), Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Since the original class is static, by definition the "extension" method doesn't need to receive an instance as a this parameter, and can simply use static methods of the original class.

Why can you not invoke extension methods directly?

Can someone explain to me why in the following the 3rd invocation of DoSomething is invalid?
( Error message is "The name 'DoSomething' does not exist in the current context" )
public class A { }
public class B : A
{
public void WhyNotDirect()
{
var a = new A();
a.DoSomething(); // OK
this.DoSomething(); // OK
DoSomething(); // ?? Why Not
}
}
public static class A_Ext
{
public static void DoSomething(this A a)
{
Console.WriteLine("OK");
}
}
Extension methods can be invoked like other static methods.
Change it to A_Ext.DoSomething(this).
If you're asking why it isn't implicitly invoked on this, the answer is that that's the way the spec was written. I would assume that the reason is that calling it without a qualifier would be too misleading.
Because DoSomething takes a parameter.
DoSomething(a) would be legal.
Edit
I read the question a bit wrong here.
Since your calling it a a normal static method, and not a extension method, you need to prefic with the class name.
So A_Ext.DoSomething(a); will work.
If you call it like a normal static method, all the same rules apply.
Your second variant works because B inhetits A, and therefore you still end up calling it as an extension method, but the third does not.
sorry about the first version above that does not work. I'll leave it to keep the comment relevant.
Extension methods are still static methods, not true instance calls. In order for this to work you would need specific context using instance method syntax (from Extension Methods (C# Programming Guide))
In your code you invoke the extension
method with instance method syntax.
However, the intermediate language
(IL) generated by the compiler
translates your code into a call on
the static method. Therefore, the
principle of encapsulation is not
really being violated. In fact,
extension methods cannot access
private variables in the type they are
extending.
So while normally, both syntaxes would work, the second is without explicit context, and it would seem that the IL generated can't obtain the context implicitly.
DoSomething requires an instance of A to do anything, and without a qualifier, the compiler can't see which DoSomething you need to invoke. It doesn't know to check in A_Ext for your method unless you qualify it with this.

What does "this" mean when used as a prefix for method parameters?

I'm sure the answer is something obvious, and I'm kind of embarrassed that I don't really know the answer already, but consider the following code sample I picked up while reading "Professional ASP.NET MVC 1.0":
public static class ControllerHelpers
{
public static void AddRuleViolations(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors)
{
foreach (RuleViolation issue in errors)
modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
}
I understand what this static method is doing, but what I don't understand is what purpose the word "this" is serving in the method signature. Can anyone enlighten me?
That is a new C# 3.0 feature called extension method.
It means, that you add a new method to your ModelStateDictionary objects. You can call it like a normal method:
yourModelStateDictionary.AddRuleViolations( errors );
See, that the first parameter (the 'this'-parameter) is skipped. It assigns just ModelStateDictionary as a valid target for your extension method.
The clue is, that you can do this with any class - even sealed or 3rd party classes, like .Net framework classes (for instance on object or string).
It means the method in question is an "extension method" and can be called as if it was a method of the class itself. See this article.
It is an extention method signature, It means the "AddRuleViolations" will be treated as an extention method of ModelStateDictionary.
From MSDN.
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.
Also see here: Extension Methods (C# Programming Guid)
It adds an extension method to all instances of ModelStateDictionary.

Categories

Resources