Reputation: 5532
A very short C# function.
public static int SizeInBytes(this byte[] a)
{
return sizeof (int) + a.Length*sizeof (byte);
}
What does "this" keyword mean in this function? What's the equivalent of this keyword in C++? Besides, what is this function trying to calculate exactly?
Upvotes: 5
Views: 459
Reputation: 498972
It is the syntax used for extension methods in C#. This is not C++.
It means that if you have a byte[]
represented by the variable buffer
, and the extension method is in scope (namespace imported, for example), you could do the following:
int buffSize = buffer.SizeInBytes();
This syntax is pure syntactic sugar - the compiler converts this to a call to the static method (on the required static class), passing in the byte[]
as the first parameter. As such, you can write the equivalent in C++, but not get the nice syntactic sugar the C# compiler gives you.
Upvotes: 7
Reputation: 8746
It marks the method as an extension method.
An extension method allows you to extend the functionality of any class, even if it's sealed.
Example:
public static class StringExtensions { public static bool IsEmpty(this string s) { return s == string.Empty; } }
Note the proper syntax includes a static method, in a static class, and the use of the this keyword.
For your second question, there is an equivalent of this in C++..... it's this. However, C++ does not support extension methods, so you'll never see it in C++ as in the code snippet you provided.
Upvotes: 8