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

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.

Related

How to extend a static class in C# [duplicate]

This question already has answers here:
Can I add extension methods to an existing static class?
(18 answers)
Closed 2 years ago.
I'm using Microsoft's Visual Studio unit testing framework (the project does therefore I have to). I'm sorely missing some of the more advanced assertions such as AreElementsEqual you find in MBUnit.
I'd like to make them.
As the class is static I can't inherit from it (to create a SuperAssert) and I can't add an extension method (as they're static methods).
I don't want to simply create another class and expect consumers to use the two different ones. How can I expand the class?
You can't. You will have to create a new one.
Or you could create an existing package, like Fluent Assertions.
As the class is static, you cannot as you say, use extension methods to 'add' further methods to the class.
The closest you can do within reason is the following:
public static class AssertExtensions
{
public static void SuperAssert(bool expression)
{
// etc...
}
}
If you are producing a tool library, asking the user to use another class should not be a problem.
If you are still concerned, why not create a base class for your test and have the users use methods within that for asserts?
For instance:
public class TestBase
{
protected void AreEqual(object obj1, object obj2)
{
Assert.AreEqual(obj1, obj2); // etc...
}
protected void SuperAssert(bool expression)
{
// etc...
}
}

Very Simple Extension Methods Explanation in Layman's terms (C#) [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are Extension Methods?
I know this questions has been asked previously, but could some provide a non-techy explanation, as simple as possible in laymens terms.
All of documentation on other answers seems to be a little far out for me
Extension methods are a way of simulating new methods on a type without actually changing the type definition itself.
I guess a layman way of explaining it is that it gives every type it's own personal entourage. They person itself is not modified they just gain a host of new abilities simply by virtue of the people who are paid to hang out with them.
I don't think it gets much simpler than the one sentence from the Wikipedia article:
"Extension methods enable you to 'add' methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."
Well, programming is inherently "techy", so I would try to learn as much as you can in order to understand the documentation. However, extension methods simply allow you to add methods that act like instance methods to an existing class that would otherwise be closed for modification.
For example, if I wrote a library that included a type Foo and did not distribute the source code you would be stuck subclassing it to add any functionality, and that would only be possible if I left the type "unsealed". With the advent of extension methods you are able to add methods to the class that you can call as you would any other method (in reality they are implemented as static methods that take a hidden first parameter to an instance of Foo, so you still don't have access to private members of the class).
Extension methods allow you to add functionality (methods) to classes you have no access to their source.
You can define a simple class:
public class A
{
public void B()
{
Console.WriteLine("B called");
this.C();
}
public void C()
{
Console.WriteLine("C called");
}
}
But what if you get A defined as:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
And you want to add function B to it? You use extension methods to do it:
public class A
{
public void C()
{
Console.WriteLine("C called");
}
}
// the extensions class, can be any name, must be public
public class Extensions
{
public static void B( this A me)
// ^ must be public static ^ indicates extension ^ type to extend ^ name of variable instead of this
{
Console.WriteLine("B called");
// instead of this, you use the name of variable you used in the parameters
me.C();
}
}
Now you can call A.B() as it was in the first example.

When to use this keyword as function argument [duplicate]

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.

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.

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