Ok, I know that property overloading is not supported in C# - most of the references explain it by citing the single-method-different-returntype problem. However, what about setters? I'd like to directly assign a value as either a string or object, but only return as a string.
Like this:
public string FieldIdList
{
get { return fieldIdList.ToString(); }
set { fieldIdList = new FieldIdList(value); }
}
public FieldIdList FieldIdList
{
set { fieldIdList = value; }
}
private FieldIdList fieldIdList;
Why wouldn't this be allowed? I've also seen that "properties" simply create getter/setter functions on compile. Would it be possible to create my own? Something like:
public void set_FieldIdList(FieldIdList value)
{
fieldIdList = value;
}
That would do the same thing. Thoughts?
You cannot overload a property: A property cannot be overloaded. It means that one can only put a single get and set accessor and mutator in a class respectively. The program given below shows what happens when we give more than one get accessor in the same class. return this .
The advantage of method overloading is that it increases code readability and maintainability. Although it is possible to have methods with the same name that perform a totally different function, it is advised that overloaded methods must have similarities in the way they perform.
Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters. When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods.
Properties are in fact a pair of get/set methods (one of which may be left out), but the property itself has additional metadata which makes it a property in the first place instead of just two methods.
Because the property signature remains invalid as per only-different-by-return-type, even if you only have a setter. If you need this, don't use a property; set-only properties aren't a good thing anyways.
One approach (you may argue amongst yourselves as to whether this is a good design choice or not) is to add a second property, which accesses the data in a different form.
However, as it is going to be parsing the string (doing significant work), it would be better not to use a property for this, but to add methods that allow you to get/set the data in a string form.
I'd go for fieldIdList providing ToString() and TryParse() interfaces - then if you need it as a string, you'd call myObject.FieldIdList.ToString() etc. This encapsulates everything tidily, allows you to convert to/from string formats anywhere in your code rather than only when accessing FieldIdLists as a member of some other class, and makes the client code really clear and easy to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With