I have a class:
public static class PictureBoxExtensions
{
public static Point ToCartesian(this PictureBox box, Point p)
{
return new Point(p.X, p.Y - box.Height);
}
public static Point FromCartesian(this PictureBox box, Point p)
{
return new Point(p.X, box.Height - p.Y);
}
}
My question is what is the use of the this
keyword in front of PictureBox
, as opposed to leaving out the keyword?
The extension method is called like an instance method, but is actually a static method. The instance pointer "this" is a parameter.
And: You must specify the this-keyword before the appropriate parameter you want the method to be called upon.
public static class ExtensionMethods
{
public static string UppercaseFirstLetter(this string value)
{
// Uppercase the first letter in the string this extension is called on.
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
class Program
{
static void Main()
{
// Use the string extension method on this value.
string value = "dot net perls";
value = value.UppercaseFirstLetter(); // Called like an instance method.
Console.WriteLine(value);
}
}
see http://www.dotnetperls.com/extension for more info.
**Edit: try below example once and again with commenting
pb.Location=pb.FromCartesian(new Point(20, 20));
to see the result**
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Size = new Size(200, 200);
pb.BackColor = Color.Aqua;
pb.Location=pb.FromCartesian(new Point(20, 20));
Controls.Add(pb);
}
}
public static class PictureBoxExtensions
{
public static Point ToCartesian(this PictureBox box, Point p)
{
return new Point(p.X, p.Y - box.Height);
}
public static Point FromCartesian(this PictureBox box, Point p)
{
return new Point(p.X, box.Height - p.Y);
}
}
}
This class contains extension methods.
The this
keyword means that the method is an extension. So the method ToCartesian
in your example extends the PictureBox
class, so that you can write:
PictureBox pb = new PictureBox();
Point p = pb.ToCartesian(oldPoint);
For more about extension methods, see the documentation on MSDN: https://msdn.microsoft.com/en-us/library/bb383977.aspx
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