Click here to Skip to main content
15,886,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
advantages of making class as property?
C#
class Emp{
p int Id;
p String Ename;
}

class SomeCls
{
public Emp emp; -> people are using class as property.
}
Posted
Updated 3-Apr-12 2:02am
v2
Comments
Paulo Zemek 3-Apr-12 9:23am    
I am not sure about what you tried to ask.
If you are concerned about the class name used as the field or property name, that is usually a more conceptual problem than a real one (if the name is short and already tells what it should tell, then there is no reason to change it only to avoid a property having a name that equals to a a class name).

But if you are asking why use a property instead of a field, it is related to run-time behavior.
Imagine that today emp is assigned during creation to a field. But, in the future, you don't initialize it immediately. If it is a property, acessing Emp will execute the code in the property, which will check for the null field and initialize it if needed.
You can change the field by a property of the same name, but already compiled code that depends in a library, for example, will cease to work (as they will expect a property, not a field). If it was always a property, even if it was a simple get/set, if you change how the get works, all code that depends on that property will continue to run, as they depend on the existence of the get_Emp method (created when you declare the property getter).
Also, if you follow naming conventions, public members always start with a capital letter (and fields should never be public except for rare cases, like the ones used when declaring Dependency Properties which are also read-only).

1 solution

Your example does not use a property at all. It just declares (presumably public in the case of Emp) fields and lets other cl;asses get on with it.

The EMP class instance is embedded within the SomeClass instance, but it is not accessed via a property - it is a public field. This is not a good idea!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900