0

In an effort to learn a little, I am trying to figure out the difference between defining a value when creating a class and using get; set; I have no idea of the terminology to look up the answer myself. Any help would be greatly appreciated. Are there certain situations you'd use one over the other. I've been using get; set; for a while, but more a matter of habit, not because i understood why.

Example:

public class Post
{
     public Guid guid = new Guid();
     public Guid userguid { get; set; } 
}
puretppc
  • 3,232
  • 8
  • 38
  • 65
Joopk.com
  • 45
  • 1
  • 8

2 Answers2

4

{ get; set; } makes auto-implemented property. You can't set default value for that property within it's declaration, so you have to use constructor.

public class Post
{
    public Guid userguid { get; set; }  

    public Post()
    {
        guid = new Guid();
    }
}

You can implement your own, non-auto property with backing field and set the field default value. This way you don't have to implement it within a contructor:

public class Post
{
    private Guid _guid = new Guid();

    public Guid userguid
    {
        get { return _guid; }
        set { _guid = value; }
    }
}

Which way to go? It's really opinion-based.

Couple things to read:

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2

The terminology you're looking for is "properties".

public Guid userguid { get; set; } 

is equivalent to:

private Guid guid;

public Guid GetGuid() {
   return guid;
}

public Guid SetGuid(Guid value) {
   guid = value;
}

For more info, read: http://msdn.microsoft.com/en-us/library/x9fsa0sw.aspx

Jack
  • 1,064
  • 8
  • 11