"this" question in C#

Hi there;

I have seen a function declaration as follows in C#.

     public static somereturnObject functionName(this className someotherobject)
        {

What is that "this" as input parameter? and what is the difference between:
     public static somereturnObject functionName(className someotherobject)
        {

Kind regards.
LVL 12
jazzIIIloveAsked:
Who is Participating?
 
Easwaran ParamasivamCommented:
It is like normal method. There is nothing special except it is for syntatic sugar. Calling the method will be part of existing class. It would be easy for us to use. Thats it!
0
 
Easwaran ParamasivamCommented:
Well. The function that you refered called Extension method. Means that you are extending (adding additional method) for existing class. this means that you are Extending the class name that you are passed in.

Say For example:

public static ExtendStringMethod(this string)
{

//Do stuff here

}


After implementing this you can call ExtendStringMethod as one of the string method.
0
 
jazzIIIloveAuthor Commented:
Hi;

Thanks for the interest in the question.

So can this be considered as inheritance in method level?

Kind regards.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
Easwaran ParamasivamCommented:
0
 
John ClaesSenior .Net Consultant & Technical AnalistCommented:
it is almost the same as you write a inheriting class and use it Every where

Only now you can stay using the base class and have the extended method available.

0
 
NavneetSoftware EngineerCommented:
Hi!

it's the way to add extension method to the type

public static somereturnObject functionName(this className someotherobject)
        {
}

So in this example an Extension Method funcionName will be added to the Type className

Say you want to add Extension to String Type as MyName

then You write like this

public static somereturnObject MyName(this String  someotherobject)
        {
}

simple example as :

http://en.wikipedia.org/wiki/Extension_method

Thanks!



0
 
ManojJainMca2004Commented:
First one is Extension Method and through out the existing assembly it will be available with that Type object.

The only thing to remember its signature is Static and must written into a non generic class ie static class.
0
 
jazzIIIloveAuthor Commented:
So. for example, this is a adding a method to a String class and calling it from an instance of that String class.

Right?

Kind regards.
0
 
TommySzalapskiCommented:
Yes. It is adding that method to the String class and allowing it to be called from instances of that class. It's just a way to add methods.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.