I'm fairly new to programming and I've been stuck on this question for awhile now, I have searched for an answer to this question throughout the internet but am still stumped as to why it is not working. The compiler says that the code below does not contain a constructor that takes 4 arguments? I don't understand why?
The code is:
public class Users
{
private int _ID;
private string _FName;
private string _LName;
private string _Address;
private string _Phone;
public int ID
{
get { return _ID; }
}
public string FName
{
get { return _FName; }
}
public string LName
{
get { return _LName; }
}
public string Address
{
get { return _Address; }
}
public string Phone
{
get { return _Phone; }
}
}
The code that is having trouble is:
public static void Insert(string FName, string LName, string Address, string Phone)
{
Users newUser = new Users(FName, LName, Address, Phone);
newUser.Save();
}
Declare a constructor that takes 4 arguments:
class User
{
public User(string firstName, string lastName, string address, string phone)
{
_fName = firstName;
....
}
}
Usage:
User user = new User("Joe", ...);
or add public setter to class properties, then use object initializer:
public string FirstName { get; set; } // notice public
Usage:
User user = new User { FirstName = "Joe", ... };
When you write new Users(...)
you are calling a constructor of the Users
class. Since you haven't defined one, the default one takes zero arguments, not four as you have used.
You could use the default constructor and set the properties with an object initializer. To do that, replace this:
Users newUser = new Users(FName, LName, Address, Phone);
with this:
Users newUser = new Users() { FName = FName, LName = LName, Address = Address, Phone = Phone };
Or, you could just add a constructor that takes four arguments, like this:
public Users(string fName, string lName, string address, string phone)
{
FName = fName;
LName = lName;
Address = address;
Phone = phone;
}
You need a constructor. It is not given. It has to be written.
I'm not very experienced with C#, but your class doesn't seem to have a constructor declared. You're declaring the variables FName, LName, Address and Phone, but they never get any value.
You might try adding this to the class Users, below your declarations:
public Users(String fname, String lname, String address, String phone)
{
FName = fname;
LName = lname;
Address = address;
Phone = phone;
}
You might also consider changing the name of 'Users' to just 'User', since each instantiation of the class represents a single User, not a collection of them.
I've seen some people trying to give a constructor an amount of parameters the same as the amount of fields it has. But if the constructor exists already in all likelihood all you need to do is:
Users user1 = new Users();