Adam Vandenberg ([info]piehead) wrote,
@ 2006-03-17 10:08:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
C#: Barenaked Properties?
Keith asks why, why, why would someone write a class full of properties that access a private member but have no custom behavior.

I agree with him up to a point, and that point is "WinForms Data Binding".

Properties and member fields are treated differently by System.Reflection. You can databind to an object property, but not a plan old member. Assuming a form with a button and a text field, the code below will throw an exception when you click the button:

using System;
using System.Windows.Forms;

namespace BindingTest
{
	public partial class Form1 : Form
	{
		DataStuff stuff;
		public Form1()
		{
			InitializeComponent();
			stuff = new DataStuff();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			textBox1.DataBindings.Add("A", stuff, "Text");
		}

		class DataStuff
		{
			public string A;
			public string B;

			public DataStuff()
			{
				this.A = "Abcde";
				this.B = "Defgh";
			}
		}
	}
}


You can't data bind to a public member. Though if you wanted to get really gross you could fake it by implementing your own Type Descriptor that synthesized properties, but we're not going to go there.



(Post a new comment)


[info]vinz_klortho
2006-03-17 03:29 pm UTC (link)
I can tell you that I do it in C++ for the simple reason that if any custom behaviour is needed later, and the customer decides to implement it, he will assuredly fondle the class's member variables in direct and unseemly ways, rather than encapsulate it.

(Reply to this) (Thread)


[info]piehead
2006-03-17 03:42 pm UTC (link)
In C#, access to a property or public member look the same to the compiler, "thing.Stuff" in either case. So syntactically, at least, the change is transparent.

Behaviorly, yeah, if the member was being reflected on then changing it to a property will blow stuff up at runtime (heh, or unit test time if you're really lucky.)

The sad thing is that both MemberInfo and PropertyInfo, the classes that encapsulate field and property access, both have "GetValue" and "SetValue" members, but they're not defined in the base class nor with a common interface, so you can't use these interchangeably.

(Reply to this) (Parent)(Thread)


[info]keith83
2006-03-17 03:49 pm UTC (link)
> but they're not defined in the base class nor with a common interface, so you can't use these interchangeably.

Wow.

(Reply to this) (Parent)


[info]keith83
2006-03-17 03:44 pm UTC (link)
Yeah, but that's in C++. C# gives you overloaded syntax for properties so that you don't have to worry about what if you need to provide custom behavior later.

(Reply to this)


Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…