Click here to Skip to main content
14,238,591 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,
I read lots of article, But I coldnt find what is the differences between Property and field

In this sample 1
class X
{
  public int Number;
}

X Instance = new X();

X.Number (I can change its value)

If I want to protect Number field to wrong access, maybe I do not want to set value from Instance Only can change main class Of X so I defined that field and property

Sample 2
class X
{
   private int Number;
   public int INumber
   {
       get {return Number;}
   }
}

But I can do this as follows
Sample 3
class X
{
   public int Number
   {
       get {return Number;}
   }
}

I couldn't understand differences between Sample 2 And Sample 3
If I want to use property, Do I must to use field, if I have not to use it why the visual studio auto generate this when I click the encapsulate the field.

What is the visual studio do in sample 3?
Is it declare a field background? Or not :)

I apologize in advance for my bad English.

Thanks a lot.
Posted
Updated 4-Oct-11 11:13am
v3
Comments
André Kraak 4-Oct-11 17:13pm
   
Edited question:
Added pre tags
Formatted text/code
Spelling/Grammar
Rate this:
Please Sign up or sign in to vote.

Solution 1

No difference if you use it the way you do. Now, imagine instead of get { return Number; } you write something else:

internal int MyNumber {
    get {
        int readValue = ComplexCalculation();
        MyHistory.Add(readValue); //remembers all the values ever read during run-time
        return readValue;
    }
}

int ComplexCalculation() { /* too complex to show here... :-) */}
System.Collection.Generic<int> MyHistory = new System.Collection.Generic<int>();
//...


That was the use of property getter. More typical use of the setter:

internal int MyNumber {
    get { /*...*/ return Number; }
    set {
        Number = value;
        MyForm.MyLabel.Text = Number; //it invalidates the form and shows new text       
    }
}


So, this is the core idea about properties: interface like that of fields, functionality like that of methods, with possible side effect. The methods are actually only getter or setter or both, but the body is arbitrary. Also, like methods the property can be static or instance one, that is without or with access to "this" parameter (reference to the instance of a declaring type). I also replaced your public with internal. So far, I see no justification for public. You really want to give the minimal possible access. Read about it: http://msdn.microsoft.com/en-us/library/ba0a1yw2%28v=VS.100%29.aspx[^].

Note, I replaced you INumber with MyNumber. Don't violate good Microsoft naming conventions. First style of naming is reserved for interfaces.

Now, this is a time for you to say: "Aha!". Come on!

—SA
   
v3
Comments
alikaras 4-Oct-11 17:36pm
   
Thanks for answer
I think I didnt tell what Im want
Is the property act like a field ?
or could I say properties are only fields interface and they are overloaded field ? I wonder that how the propertys work background like a field ?
In this code

Collapse | Copy Code
It seems only property but I wonder that have there a field background
class X
{
public int Number
{
get {return Number;}
}
}
I think I couldnt tell
I wonder differences between property and field how to work background

Collapse | Copy Code
class X
{
private int Number;
public int INumber
{
get {return Number;}
}
}
and

Collapse | Copy Code
class X
{
public int Number
{
get {return Number;}
}
}
Thanks a lot
   
I think I answered in full, don't see what's not clear. "Overloaded field", what is it? Just to make it clear: in a language, there is nothing which is "overloaded" (because nothing is "loaded"); this is just a bad but "standard" term for different methods with the same name, no more, no less.

How properties work in background? Like methods, static or instance one. Getter has no parameters and returns value, setter has (implicit) input by-value parameter which is always called "value" and returns void. That's is.

A field behind implementation of the property is very usual, but it can be anything. Any code returning value under get, any code accepting by-value parameter value under set. Strictly speaking, a getter does not have to return a value of any fields (it only has to return some value of declared property type), a setter does not have to modify or assign value to any object.

Properties are methods with described signatures which, on the user's side, only syntactically look like reading a field value and assignment a value to a field.
--SA
Simon Bang Terkildsen 4-Oct-11 19:11pm
   
My 4, though I want to state two rules about getters which I feel very strongly about and do not like to see broken.
getters must not change the state of the object.
getters must return the same value/reference each time they are called in between state changes.
There are no exceptions to the above if you need to change the object state when you retrieve a value you must use a method instead.

Notice I do not write should but must and that's because I feel so strongly about it. If you do not follow the two points I stated then some developer who think hey I want the value of this property could easily break the code. If any of my developers did either of the above I would revert to my army days and treat them as armed enemy combatants that way I'm sure they can never do it again.

so in short
ComplexCalculation(); must be pure! - no state changes, and the same integer must be returned in between state changes!
MyHistory.Add(readValue); reverting to army days.. My weapon of choice the danish LMG M/62(Nazi Saw) originally the German MG42

I feel so strongly about this that I only gave you a 4 instead of a 3 because you have my out most respect. And I must say I'm surprised you broke those rules, as you always are very, very thorough.
Simon Bang Terkildsen 4-Oct-11 19:20pm
   
There is ONE exception and that is when you do some lazy loading

get { return _field ?? (_field = new Object() ); }

This could be used in for example the implementation of the Singleton pattern. or when you need to retrieve a value from a network resource, so you only do it if the value is actually used.
   
Thank you for the note, Simon.

I did not break any rules. What you we discussing? The notion of .NET or best practices?
I only discuss the mechanism here without any concern to best practices. If you discuss language/platform feature, it's good to know its bounds. Modifying getter is possible and not prohibited, period. Also, this is a distinct distinction from a field, which is good to know. Everything else (such as access modifiers) is no different, except separate modifiers for getters and setters. Virtual getters/setters are no different from methods.

Now, about best practices. I would say -- your rule is quite valuable, as a rule of thumb. As to exclusions -- you already demonstrated one, which is by the way a very good pattern to use. Are there other exclusions? Well, there could be. I may happen to invent one, you may happen to invent another -- I cannot be sure. I don't see a great law of nature in such limitation. I prefer a different rule -- never say "never". If you don't like "contradicting paragraphs", say: almost never say "never".
--SA
Simon Bang Terkildsen 5-Oct-11 2:32am
   
Hmm there seems to something wrong with the CP notification I wasn't notified of this reply, it seems to happen a couple of times per day.

Well back to the issue. This is something I feel extremely strongly about and I do not see that I ever would ever accept any other exception than the one I mentioned.
I realize some might have a difference view, but they are heretics. Yeah this two rules I'm extremely religious about and I believe the only ones. Also if you break the rules you'll be in trouble if you're using Code Contracts as Code Contracts assumes property getters to be pure so if it's not pure you might as well not use Code Contracts.

I really want to come to an agreement here but I can't budge one nanometer on this.
Rate this:
Please Sign up or sign in to vote.

Solution 3

It might help you,

Fields[^]

Properties[^]

:)
   
Comments
alikaras 4-Oct-11 18:02pm
   
May be I think absurd things so I apologize if it is true :D
Only I wonder if I declare property not with a field
like this
<pre lang="c#">
public int MyProperty { get; set; }
</pre>
I can use it like a field,But I didnt declare field I declare only property, how is this going ?
have there a field background of property ?
Mohammad A Rahman 4-Oct-11 18:54pm
   
.Net Reflector will give all answer for you questions. Anyway, for the property you declare public int MyProperty { get; set; }, in the background .Net will create following private field
[CompilerGenerated]
private int <myproperty>k__BackingField;

and for the get and set of MyProperty will have following code to access compiler generated private field,

[CompilerGenerated]
public void set_MyProperty(int value)
{
this.<myproperty>k__BackingField = value;
}
[CompilerGenerated]
public int get_MyProperty()
{
return this.<myproperty>k__BackingField;
}

Hope it helps :)
alikaras 5-Oct-11 0:00am
   
Thanks to all who
Mohammad A Rahman said exactly what I'm looking for,
I would therefore like to thank you.
Good work everyone
Mohammad A Rahman 5-Oct-11 5:25am
   
Thank you very much Ali :)
BillWoodruff 5-Oct-11 3:22am
   
+5: an excellent answer Mohammad, best, Bill
Mohammad A Rahman 5-Oct-11 5:24am
   
Thank you very much Bill :)
Rate this:
Please Sign up or sign in to vote.

Solution 4

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. (MSDN)
public int MyProperty { get; set; }

I can use it like a field.
I understand that properties provides like a guard or functionally for field
but how it is work, only propery with out field, actually it is a field ? or overloaded field
If I wrong tell me, I wont write a more. Because Maybe you have got lots of work :)
Really I wonder this and I read turkish books but I didnt find like my search
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100