about using property

T

Tony Johansson

Hello!

Below is a definition of a struct called Second.

Now to my question as you can see this struct has field called value.
The struct has a property connected to this field called Value which is a
getter.
For example when I want to read this value field from within a member in the
struct Second is the recommended way
to read it by using the value field directly or by using the get property
Value ?

struct Second
{
private int value;

public Second(int initialValue)
{ value = System.Math.Abs(initialValue) % 60; }


public static implicit operator Second(int arg)
{ return new Second(arg); }

public int Value
{ get { return value; } }

public static bool operator==(Second lhs, Second rhs)
{ return lhs.value == rhs.value; }


public static bool operator !=(Second lhs, Second rhs)
{ return lhs.value != rhs.value; }

public override bool Equals(object other)
{ return (other is Second) && Equals((Second)other); }

public bool Equals(Second other)
{ return value == other.value; }

public override int GetHashCode()
{ return value; }

public static Second operator++(Second arg)
{
arg.value++;
if (arg.value == 60)
{
arg.value = 0;
}
return arg;
}
}

//Tony
 
M

Marc Gravell

Personally I would tend to use property access throughout, until I
*know* that this is an issue. In many cases the JIT will "inline" the
property, so it acts the same as direct field access anyway -
especially since this is a simple pass-thru and sealed (not virtual).
It means that if you ever change the logic to do something different
you don't have to re-write much code...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top