I read somewhere that having public properties is preferable to having public members in a class.
Is this only because of abstaraction and modularity? Are there any other over-riding reasons?
The property accesses are conerted into function calls by the compiler. For properties without a backup store (e.g.
public string UserName { get; set; }
), what would be the performance overhead compared to a direct member access? (I know it shouldn't usually make a difference but in some of my code, properties are accessed millions of times.)
Edit1: I ran some test code over integer members and Properties and the public members were about 3-4 times as fast as Properties. (~57 ms. vs ~206 ms. in Debug and 57 vs. 97 in Release was the most common run value). For 10 million reads and writes, both are small enough not to justify changing anything.
Code:
class TestTime1
{
public TestTime1() { }
public int id=0;
}
class TestTime2
{
public TestTime2() { }
[DefaultValue(0)]
public int ID { get; set; }
}
class Program
{
static void Main(string[] args)
{
try
{
TestTime1 time1 = new TestTime1();
TestTime2 time2 = new TestTime2();
Stopwatch watch1 = new Stopwatch();
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (int i = 0; i < 10000000; i++)
{
time2.ID = i;
i = time2.ID;
}
watch2.Stop();
watch1.Start();
for (int i = 0; i < 10000000; i++)
{
time1.id = i;
i = time1.id;
}
watch1.Stop();
Console.WriteLine("Time for 1 and 2 : {0},{1}",watch1.ElapsedMilliseconds,watch2.ElapsedMilliseconds);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.In.ReadLine();
}
}