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.
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.
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.
The in, ref, and out Modifiers ref is used to state that the parameter passed may be modified by the method.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With