Set Accessor best practices question

  • Thread starter Thread starter Robert Zurer
  • Start date Start date
R

Robert Zurer

If I have only a simple assignment in a set accessor which is more
perfomant?

public DateTime StartTime
{
get{return startTime;}
set
{
if(startTime!= value)
{
startTime= value;
}
}
}

OR

public DateTime StartTime
{
get{return startTime;}
set{startTime= value;}
}

or is there no difference?

TIA

Robert Zurer
 
Hi Robert,

In your case I would think it would be insignificant difference, though I would probably use the last one. The time taken to assign startTime the same value is probably shorter than actually testing for equality.
 
Hi Robert,

In your case I would think it would be insignificant difference, though I would probably use the last one. The time taken to assign startTime the same value is probably shorter than actually testing for equality.

I have been doing so all alongm however I've seen it written that way by
others so many times that I thought there might be something that I was
unaware of under the hood. (Sort of like using the as operator and then
checking for null generates fewer IL lines than using the is operator).

Thanks for your answer.
 
Robert said:
If I have only a simple assignment in a set accessor which is more
perfomant?

One thing to consider in general is the expense of the assignment. In
this case and most cases in C# it's pretty trivial. If it was a struct
(by value) that was fairly complex then adding the check might be valuable.

David
 
David Bradley said:
Robert Zurer wrote:
One thing to consider in general is the expense of the assignment. In
this case and most cases in C# it's pretty trivial. If it was a struct
(by value) that was fairly complex then adding the check might be valuable.

Actually - DateTime is a struct unless I'm mistaken so we are dealing with by value. But, it is not an overly complex one, so you
are right, in this case it probably would not make much of a difference.
 
Back
Top