Property get vs get-like function

I was wondering if there are any differences between using property getter and simple get function.. well there’s no difference, but lets see

public class PropVsFun
{
    private int _x;
    public int x { get { return _x; } set { _x = value; } }
    public int getX() { return _x; }

    public int pX;

    public PropVsFun(int X)
    {
        _x = X;
        pX = X;
    }
}

void test()
{
    PropVsFun pvsf = new PropVsFun(10);
    int a, b, c;
    // Property
    a = pvsf.x;
    // Function get
    b = pvsf.getX();
    // Variable
    c = pvsf.pX;
}

Results:
There is no difference between IL codes of property get and get function as we see below:

IL_0009: callvirt instance int32 CodeEfficiencyTests.PropVsFun::get_x()
IL_000e: pop
IL_000f: ldloc.0
IL_0010: callvirt instance int32 CodeEfficiencyTests.PropVsFun::getX()
IL_0015: pop
IL_0016: ldloc.0
IL_0017: ldfld int32 CodeEfficiencyTests.PropVsFun::pX
IL_001c: pop
IL_001d: ret

Advertisement
This entry was posted in C# and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s