[C#] what is {get;set;}  +   [Desktop/Windows]   |  2017.03.08 21:08

These are declarations for a Person class.

protected int ID { get; set; }
protected string Title { get; set; }
protected string Description { get; set; }
protected TimeSpan jobLength { get; set; }

How do I go about using the get/set? In main, I instantiate a

Person Tom = new Person();

How does Tom.set/get??

I am use to doing C++ style where you just write out the int getAge() and void setAge() functions. But in C# there are shortcuts handling get and set?

shareimprove this question
1 
You can't access the properties from outside the Person class (and derived classes) if you declare them as protected... – Thomas Levesque Jan 11 '11 at 20:49
1 

Assuming you have access to them (the properties you've declared are protected), you use them like this:

Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;

These are properties. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of automatically implemented properties where the compiler is adding a backing field. You can write the code yourself though. For example, the Title property you've declared is like this:

private string title; // Backing field
protected string Title
{
    get { return title; }  // Getter
    set { title = value; } // Setter
}

... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.

You can make one part of a property more restricted than another. For example, this is quite common:

private string foo;
public string Foo
{
    get { return foo; }
    private set { foo = value; }
}

or as an automatically implemented property:

public string Foo { get; private set; }

Here the "getter" is public but the "setter" is private.

shareimprove this answer
2 
Yes, but they're declared protected, so you can't do that... – Thomas Levesque Jan 11 '11 at 20:48
1 
@Thomas: Depending on which class we're in... will edit though. – Jon Skeet Jan 11 '11 at 20:49
4 
+1 for "except that the backing field is given an 'unspeakable name'". Very Lovecraftian. – Dan J Jan 12 '11 at 1:08
   
@djacobson: I wish I'd come up with the term - but I think I first got it from Eric Lippert. I don't know whether he thought it up or someone else in the C# team... or whether it's older than C#. It's a lovely term though, I agree. – Jon Skeet Jan 12 '11 at 6:25



 
TRACKBACK 0    COMMENT 0

 


비밀글로 저장  
 
 
<<이전   | 1 | 2 | 3 | 4 | ··· | 730 |   다음>>
 

rednine's Blog is powered by Daum & tistory