I want my object to be able to type in an double or a string such as getting an input for salary. I have my code working with a property that allows for a double only. I know that property overloading isn’t supported from the other postings at this site. I also know that setters are going to allow me to get an string input for salary. I don’t understand how to overload. I have some of the template code here:
private double salary = 20000;
public Employee()
{
}
public Employee(double sal)
{
salary = sal;
}
public double Salary
{
get { return salary; }
set { salary = value; }
}
public void SetSalary(string sal)
{
salary = Convert.ToString(sal);
}
Error code:
can not implicitly covert type string to double
I want to be able to have an object be able to overload salary using a setter in C#. I am a student and understand most of the basics. Thanks ahead of time for any help.
You are converting the parameter, which is already a string, to a string, and trying to assign it to a field that is of type double.
Note that these conversions can fail if the string is not in the proper numeric format.
double.TryParsecould be useful, but it’s probably an exception that needs to propogated to your callers when they send an invalid input. With all of that said, I would leave it up to your callers to convert the value to the appropriate type and simply expose the double property. There’s no need to complicate matters in your class.For that matter, for a value that is supposed to represent a salary, you should consider using the more appropriate
decimaltype. It’s tailored for storing financial values.