"Yin99" <ws@ziowave.comwrote in message
news:11**********************@19g2000hsx.googlegro ups.com...
>I programmed JAVA for a while and starting C#, and was experimenting
with
"Properties". Question I have, is what is the benefit? JAVA does
not have the concept
of properties, so what is JAVA missing and why is it so great C# has
it? Thanks,
Yin
As other have pointed out, properties are the C# equivalent of
setter/setter methods.
You could write C# code using the same getter/setter syntax as in Java
if you prefer, but properties improve the readability of the code. Below
are similar classes in Java and in C#.
------------------------------------
//// Java ////
public class Foo
{
private int x = 0;
public int getX() {return x;}
public void setX(int value) {x = value;}
}
//// C# ////
public class Foo
{
private int x = 0;
public int X
{
get {return x;}
set {x = value;}
}
}
-----------------[ setter example ] ----------------
// Java - You call the setter method explicitly
Foo foo = new Foo();
foo.setX(5);
// C# - X looks like a public field,
// but it really calls the setter under the covers
Foo foo = new Foo();
foo.X = 5;
-----------------[ getter example ] ----------------
// Java - You call the getter method explicitly
int x = foo.getX();
// C# - X looks like a public field,
// but it really calls the getter under the covers
int x = foo.X;
-----------------[ += example ] ----------------
// Java : += logic is a bit painful to look at
// add 2 to foo.x
foo.setX(foo.getX + 2));
// C# - Under the covers, this is doing the same thing as the java code
foo.X+=2;
-----------------
If you are interested in the underlying functionality try running this
code.
It explicitly shows how the setter/getter are called
using System;
public class Test
{
public static void Main()
{
Foo foo = new Foo();
foo.X = 5;
Console.WriteLine("Foo.X:{0}", foo.X);
foo.X += 2;
Console.WriteLine("Foo.X:{0}", foo.X);
}
}
public class Foo
{
private int x = 0;
public int X
{
get
{
Console.WriteLine("Foo.getX:{0}", x);
return x;
}
set
{
x = value;
Console.WriteLine("Foo.setX({0})", x);
}
}
}
Hope this helps
Bill