Tuesday, June 3, 2008

Yet Another reason why Properties should be used instead of Fields


Today, I did a little experiments on Properties VS Fields. It is better to use properties especially when that property is to interact with the other DLLs or external Assemblies.


Scenario: library.library.Name is a field in my library which I refer in my winapp. I executed it worked fine. I wanted to validate Name field for special characters so I decided to change “Name” (At present a Field in library) to a property so that I could validate it in the set property.


As the member name and the return type (string) did not change I did not recompile my winapp. But I got the following exception “Field not found” as it’s a property now.



Conclusion: When you need a member to interact with the external assemblies or DLLs or EXEs make it a property instead of field. This enables you to add validators later within your class.




No comments: