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?
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.