Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of "this" keyword here?

Tags:

c++

c#

this

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?

like image 397
derekhh Avatar asked Nov 17 '11 19:11

derekhh


2 Answers

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.

like image 198
Didaxis Avatar answered Nov 13 '22 13:11

Didaxis


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.

like image 36
Oded Avatar answered Nov 13 '22 13:11

Oded