Specify only the setter on the set / receiver

I use getters and seters to instantiate the class.

Is it possible to configure a value set without having to have a private variable and do it directly by type?

For example, if my class is:

public class Cat() { public String Age{get; set; } } 

and I want to create an instance of it:

 new Cat({Age: "3"}); 

Now, if I have a ConvertToHumanYears function that I want to call before it is saved, I would assume that it is:

 public class Cat() { public String Age{get; set{ value = ConvertToHumanYears(value); } } 

But the above (and many of them) seem to return errors. Is it possible to do something like this without having an extra private variable that I set and get?

+6
c # windows-phone-7 silverlight
source share
2 answers

You cannot use the auto property for getter and have a definition for setter.

it either

 public class Cat() { public String Age{get; set; } } 

or

 public class Cat() { private String _age; public String Age{ get{ return _age; } set{ _age = ConvertToHumanYears(value); } } } } 
+17
source share

How about this?

 public class Cat { public string Age { get; private set; } } 

You must have an installer, but it can only be called inside the class itself.

Then you can create a constructor that allows you to set the value:

 public Cat(string age) { Age = age; } 

or

 public Cat(string age) { Age = ConvetToHumanYears(age); } 
+2
source share

All Articles