Using Properties or Fields

  • (2 Pages)
  • +
  • 1
  • 2

27 Replies - 1657 Views - Last Post: 06 May 2012 - 04:08 PM

#16 bonyjoe  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 548
  • Joined: 08-September 10

Re: Using Properties or Fields

Posted 29 April 2012 - 06:04 AM

Get and set are just keywords to show the compiler what to do when the property is called or assigned to.

So if you use the set to set the private field when you return it using get you will get whatever it was set to. Or if you set the private field directly when you return it via the property get you will get whatever it was set to. For example

private String _test = "Test";

public String Test
{
  get{return _test;}
  set{_test = value;}
}

String newString = Test;
//newString value will be "Test" as that is what the get returned

Test = "testSet";
//_test is now "testSet";

_test = "directlySet";
//_test is now "directlySet" and the Test get will return "directlySet"



So your question about ambiguity is as long as your get returns the correct private field then the field and property will remain the same.

If you do not declare method bodies for get or set
public String Test
{
  get;
  set;
}



then it will be the same as if you declared a private field as the compiler will generate one for you using the default constructor, you just will not be able to access the field directly

edit:

Also you are being told that set has no method body because you have given get one, so therefore it won't generate a method for the set. If you define get you either have to define a set or not have a set at all and vice versa.

You seem to be thinking of the property as its own field as well. The property holds no value, when you call the property it calls the get method, it does not remember the result, when you assign to it the set method is called, it does not remember the result. So calling the get method doesn't "update the property" it just returns whatever the get method says to return.

This post has been edited by bonyjoe: 29 April 2012 - 06:09 AM

Was This Post Helpful? 2
  • +
  • -

#17 DanielLeone  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 177
  • Joined: 04-February 12

Re: Using Properties or Fields

Posted 29 April 2012 - 04:49 PM

Thanks for the clarifications bonyjoe,

I'm glad you and the rest of the people on this thread have cleared things up for me, and I think that I finally understand how to use, and how Properties work.

Your help is greatly appreciated,
Daniel,
Was This Post Helpful? 1
  • +
  • -

#18 racidon  Icon User is offline

  • D.I.C Head

Reputation: 59
  • View blog
  • Posts: 172
  • Joined: 27-August 11

Re: Using Properties or Fields

Posted 30 April 2012 - 12:50 AM

@BonnyJoe - You kind of covered why you would to inherit fields instead of just using the inherited properties.
Properties are meant to be used by outside classes, with exception of such methods like Public, that may need the methods within the property to get the correct data. But if you had say 5 levels of inheritance with a load of objects that didn't inherit fields, you'd be running a method for each and every one which is both messy and can get slow as data increases.

@DanielLeone - A property is a specialised method. Depending how it's called depends on the two actions.

"PropertyName" - Will call the "get" method
"PropertyName = Value" - Will call the "set" method where 'Value' is the 'value' keyword.

A get method can also assign to the values it's getting. An example would be in 2d XNA, you may have an animation. Property would be called "CurrentFrame"

Code:
public Texture2D CurrentFrame
{
   get
   {
      if(++_frameIndex >= _frames.Length)
      {_frameIndex = 0;}
      return _frames[_frameIndex];
   }
}


Was This Post Helpful? 2
  • +
  • -

#19 DanielLeone  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 177
  • Joined: 04-February 12

Re: Using Properties or Fields

Posted 04 May 2012 - 04:24 AM

Hello once again,

You said that if you don't declare a body for get and set, then the compiler will basically generate a private method for you.

However, I was using this for a list, and it doesn't work if you don't declare a body.

This is the Property.

        public List<MenuEntry> MenuEntries
        {
            get; // { return menuEntries; }
            set; // { menuEntries = value; }
        }



This is setting it.


            ScreenManager.CurrentScreen.MenuEntries.Add(this);



It returns with an error:
"Object reference not set to an instance of an object."

Note : Screen Manager is a class, and CurrentScreen is a property.
This works uncommenting the above code, so setting it to a private field.

I think this may be because the private field starts with = new List<MenuEntry>();

And that is generally the reason for this error, so I was wondering why this wouldn't actually work though.

Any advice is appreciated,
Daniel,
Was This Post Helpful? 0
  • +
  • -

#20 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Using Properties or Fields

Posted 04 May 2012 - 05:22 AM

This error isn't really because you're using a property, it's because you forgot to initialize your list :)

An auto-implemented property will create a private, anonymous backing field. They wont initialize them for you.

So, in your constructor, just add this:
MenuEntries = new List<MenuEntry>();



Just to add to the discussion, it is strongly suggested that you use properties whenever necessary. In smaller, less complex classes, properties may not be necessary at all. Generally, though, in larger classes that contain significant behavior, public properties become necessary.

Properties are great for many reasons, but here's one I didn't see mentioned. Properties allow you to very easily control whether your objects are mutable or immutable. This is an important concept.

For example, this class is mutable:
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}


Client code can change the objects in the class once they are created.

This class is immutable:
public class Person
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public int Age { get; private set; }
}


Client code can retrieve and use the values of the objects in this class, but cannot change them.

There are several more benefits yo using properties, and as you continue to develop the need will become more apparent.

This post has been edited by lesPaul456: 04 May 2012 - 05:25 AM

Was This Post Helpful? 2
  • +
  • -

#21 DanielLeone  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 177
  • Joined: 04-February 12

Re: Using Properties or Fields

Posted 04 May 2012 - 06:19 AM

Thanks lesPaul456,

That was what I was thinking, but you explained it well for me :)

Also thanks for the terminology (mutable and immutable), I was already using that, because I have seen others do it on video tutorials and so fourth, but I now know what it is called anyway :).

So now that I understand how to use just get and set of there own, it that what I should do if I would only get and set it anyway ( sorry for the bad explanations ;)) Like this:

private bool myBool;
public bool MyBool
{
  get {return myBool;}
  set {myBool = value;}



Should anyone ever type this when using C#4.0 ( I think that is what it is?) now that you don't actually have to?

And if I did for some reason I was using the above example, when referring to the bool in the same class, should I be using myBool or MyBool?


Thanks once again for the reply,
Daniel,

This post has been edited by DanielLeone: 04 May 2012 - 06:24 AM

Was This Post Helpful? 0
  • +
  • -

#22 Kilorn  Icon User is offline

  • XNArchitect
  • member icon



Reputation: 1355
  • View blog
  • Posts: 3,528
  • Joined: 03-May 10

Re: Using Properties or Fields

Posted 04 May 2012 - 06:46 AM

You would use myBool for any checks in that class, but use MyBool for instances that are accessed outside of that class.

As for typing out the gets and sets, I've always typed them out completely, and I will continue to do so. Another nice little feature about properties is that you can make them read only, or immutable, where they cannot be changed from outside that class, simply by not having a mutator, or set, in the property. lesPaul456 already mentioned mutable and immutable, but his example involved private mutators, where mine excludes the mutators completely.
// Read and Write capable or Mutable
private int x;
public int X
{
    get { return x; } // Accessor
    set { x = value; } // Mutator
}

// Read only or Immutable
private int y;
public int Y
{
    get { return y; } // Accessor
}


This post has been edited by Kilorn: 04 May 2012 - 06:51 AM

Was This Post Helpful? 3
  • +
  • -

#23 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Using Properties or Fields

Posted 04 May 2012 - 07:17 AM

It's a good habit to get into writing readable and maintainable code, especially if you plan on having a career in development. Auto-implemented properties are lightweight and readable. Honestly, besides that, there's not much difference. In the end, it's a matter of preference. Just remember that using properties when necessary is a good programming practice.

@Kilorn: Yep. Just remember that leaving out the setter in auto-implemented properties will make it read-only to both client code and to the class itself (which means it will always be set to its default value or null).
Was This Post Helpful? 2
  • +
  • -

#24 racidon  Icon User is offline

  • D.I.C Head

Reputation: 59
  • View blog
  • Posts: 172
  • Joined: 27-August 11

Re: Using Properties or Fields

Posted 05 May 2012 - 02:10 AM

@Kilorn

To add to lesPaul456, having only a get will only make it "immutable" when on data structures are being used, once you introduce "Reference Types" such as a List<T> you're able to modify the values.

Example for DanielLeone

public List<int> Indicies
{
get{return _indicies;}
}


allows you to do the following outside the class

Indicies = new List<int>;

As the "get" returns a reference to memory rather than just the value itself.
But this can be fixed with the following:

public List<int> Indicies
{
get{return (List<int>)_indicies.Clone();}
}

That will be more load on the cpu (only noticeable with large repeats/data) but will return a new area in memory that will be disposed of shortly after. Any assignment to it will not be saved.
Was This Post Helpful? 1
  • +
  • -

#25 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Using Properties or Fields

Posted 05 May 2012 - 08:55 PM

View Postracidon, on 05 May 2012 - 05:10 AM, said:

@Kilorn

To add to lesPaul456, having only a get will only make it "immutable" when on data structures are being used, once you introduce "Reference Types" such as a List<T> you're able to modify the values.

Example for DanielLeone

public List<int> Indicies
{
get{return _indicies;}
}


allows you to do the following outside the class

Indicies = new List<int>;

As the "get" returns a reference to memory rather than just the value itself.
But this can be fixed with the following:

public List<int> Indicies
{
get{return (List<int>)_indicies.Clone();}
}

That will be more load on the cpu (only noticeable with large repeats/data) but will return a new area in memory that will be disposed of shortly after. Any assignment to it will not be saved.


Just to clarify, in C# all classes are reference types.

A property that provides only a getter is read only, even in the example you provided.
Was This Post Helpful? 1
  • +
  • -

#26 racidon  Icon User is offline

  • D.I.C Head

Reputation: 59
  • View blog
  • Posts: 172
  • Joined: 27-August 11

Re: Using Properties or Fields

Posted 06 May 2012 - 04:15 AM

View PostlesPaul456, on 05 May 2012 - 08:55 PM, said:

View Postracidon, on 05 May 2012 - 05:10 AM, said:

@Kilorn

To add to lesPaul456, having only a get will only make it "immutable" when on data structures are being used, once you introduce "Reference Types" such as a List<T> you're able to modify the values.

Example for DanielLeone

public List<int> Indicies
{
get{return _indicies;}
}


allows you to do the following outside the class

Indicies = new List<int>;

As the "get" returns a reference to memory rather than just the value itself.
But this can be fixed with the following:

public List<int> Indicies
{
get{return (List<int>)_indicies.Clone();}
}

That will be more load on the cpu (only noticeable with large repeats/data) but will return a new area in memory that will be disposed of shortly after. Any assignment to it will not be saved.


Just to clarify, in C# all classes are reference types.

A property that provides only a getter is read only, even in the example you provided.

I see I made the assumption on the "Property = new value" working, but isn't (im)mutable to do with values that can and cannot be changed? The list can, I could do "Property.Clear()" "Property.Add(value)" etc etc, there's only one way to prevent that and it's to clone the data before returning it.
I'm also aware that classes are reference types so are arrays of any kind, but structures or enums(can't remember this one to be exact) aren't
Was This Post Helpful? 0
  • +
  • -

#27 bonyjoe  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 548
  • Joined: 08-September 10

Re: Using Properties or Fields

Posted 06 May 2012 - 08:27 AM

View Postracidon, on 06 May 2012 - 12:15 PM, said:

I see I made the assumption on the "Property = new value" working, but isn't (im)mutable to do with values that can and cannot be changed? The list can, I could do "Property.Clear()" "Property.Add(value)" etc etc, there's only one way to prevent that and it's to clone the data before returning it.
I'm also aware that classes are reference types so are arrays of any kind, but structures or enums(can't remember this one to be exact) aren't


Or there are other solutions such as readonlycollections or this handy method
Was This Post Helpful? 1
  • +
  • -

#28 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Using Properties or Fields

Posted 06 May 2012 - 04:08 PM

@racidon: The object itself is read only, the underlying collection is not. As bonyjoe pointed out, a ReadOnlyCollection can be used to prevent client code from modifying collections.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2