C# question: How can I use the constructor:
AcctHolder ah1 = new AcctHolder("Dumitru", "St", "Bucharest");
and be able to obtain ah1.Fname? (instead of null)
using System;
namespace ConsoleApplication1
{
class ATM
{
public static void Main(string[] args)
{
AcctHolder ah1 = new AcctHolder("Dumitru", "St", "Bucharest");
Console.WriteLine(ah1.FName); //returns null - why???
AcctHolder ah2 = new AcctHolder();
ah2.FName = "Dumi";
Console.WriteLine(ah2.FName); // returns "Dumi"
Console.ReadKey();
}
public class AcctHolder
{
private string fname, lname, city;
public string FName { get; set; }
public string LName { get; set; }
public string City {
get { return city; }
set { city = value; }
}
public AcctHolder(string a, string b, string c)
{
fname = a;
lname = b;
city = c;
}
public AcctHolder()
{
}
}
}
}
returns null - why???
Because you are initializing unrelated fields in the constructor not the backing fields of the properties. You don't need them with auto-implemented properties:
public class AcctHolder
{
public string FName { get; set; }
public string LName { get; set; }
public string City { get; set; }
public AcctHolder(string a, string b, string c)
{
FName = a;
LName = b;
City = c;
}
public AcctHolder()
{
}
}
If you want to keep the backing fields:
public class AcctHolder
{
private string fname;
public string FName
{
get { return fname; }
set { fname = value; }
}
private string lname;
public string LName
{
get { return lname; }
set { lname = value; }
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
public AcctHolder(string a, string b, string c)
{
fname = a;
lname = b;
city = c;
}
public AcctHolder()
{
}
}
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