Leif K-Brooks wrote:
Is it possible to create a class in C# which behaves like another
object's property? Here's an example of what I want to be able to do,
using made up syntax:
class PropertyObject
{
private int value = 0;
public static int operator get(PropertyObject p)
{
return p.value;
}
public static void operator set(PropertyObject p, int value)
{
p.value = value;
}
}
class Foo
{
public int X = new PropertyObject();
}
Right now I can do the same thing with an explicit property in Foo:
class Foo
{
private PropertyObject x = new PropertyObject();
public int X
{
get
{
return x.Get();
}
set
{
x.Set(value);
}
}
}
But doing it that way leads to very verbose code, especially if the
property is used many times. Is there a better way?
No. And believe me, your way isn't better. Let's explain a few things
about .NET and code/data at runtime.
If you have 10 classes, which each have 10 properties, you have 100
getters and 100 setters. These are methods in the objects at runtime
and take no memory, other than the code bytes. .NET shares the code of
a class among all instances of that class. However your approach would
require a new instance of the propertyobject for each property, in each
instance of the class, so say if each instance of those classes is in
memory you have 100 propertyobject instances. That's not efficient.
Code is cheap, do as much as you can in code, instead of in objects.
So write out the get/set clauses of properties in each class, it's
better.
FB
--
------------------------------------------------------------------------
Get LLBLGen Pro, productive O/R mapping for .NET:
http://www.llblgen.com
My .NET blog:
http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------