Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this parameter modifier in C#?

Tags:

I'm curious about this code snippet:

public static class XNAExtensions {     /// <summary>     /// Write a Point     /// </summary>     public static void Write(this NetOutgoingMessage message, Point value)     {         message.Write(value.X);         message.Write(value.Y);     }     // ... }; 

What does the this keyword mean next to the parameter type? I can't seem to find any information about it anywhere, even in the C# specification.

like image 828
Ivan Avatar asked Jan 15 '11 14:01

Ivan


People also ask

What is parameter modifiers in C sharp?

C# out Parameter In some of the methods, we need to return a value to a calling method. Instead of using a return statement, for this C# provides a modifier for a parameter as out. The usage of out can be better understood by the following program. class Program.

What is out _ in C#?

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values.

Is used to state that the parameter passed must be modified by the method?

The in, ref, and out Modifiers ref is used to state that the parameter passed may be modified by the method.

What is parameter in C# with example?

In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment.


2 Answers

That's an extension method.

The syntax means you can call the method as if it was a member of the NetOutgoingMessage class:

var msg = new NetOutgoingMessage(); msg.Write(somePoint); 

This is basically rewritten by the compiler to:

var msg = new NetOutgoingMessage(); XNAExtensions.Write(msg, somePoint); 

It's just nice syntactical sugar.

like image 136
Blorgbeard Avatar answered Oct 01 '22 17:10

Blorgbeard


That is how an extension method is defined.

What this essentially means is that, even though this method is contained in an encapsulating static class, when using the type specified (in the extension method parameters labelled this) such a method will be automatically exposed such that:

var typeInstance = new TypeWithExtensionMethod(); typeInstance.ExtensionMethod(anyParametersRequiredButNotTypeInstance); 

Is possible, as opposed to:

var type = new TypeWithExtensionMethod(); ExtensionMethods.ExtensionMethod(typeInstance, anyOtherParametersRequired); 
like image 24
Grant Thomas Avatar answered Oct 01 '22 17:10

Grant Thomas