I have a DB table with users, some are ‘agents’ and some are ‘clients’. In my C# project, I have a User superclass and an Agent and Client subclass. Agent and Client extends User.
I am having some basic problems when casting or changing a User object to an Agent or Client object. I don’t really know why. It’s probably rather basic, but I don’t know what’s wrong.
public class User
{
public int UserId { get; set; }
public string UserType { get; set; }
public DateTime DateCreated { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public User()
{
}
}
public class Agent : User
{
public string Company { get; set; }
public string CompanyReg { get; set; }
public string SecurityQuestion { get; set; }
public string SecurityAnswer { get; set; }
public string Description { get; set; }
public int AccountBalance { get; set; }
public bool WantsRequests { get; set; }
public string ImageUrl { get; set; }
public Agent()
{
}
}
public class Client : User
{
public string Country { get; set; }
public string IP { get; set; }
public Client()
{
}
}
Now why can’t I do this:
public User GetUser(int userid)
{
User user = new User();
User returnuser = user;
string sql = "SELECT usertype, datecreated, email, name, phone, country, ip, company, companyreg, securityquestion, securityanswer, description, accountbalance, aothcredits, wantsrequests FROM ruser WHERE userid=@userid";
try
{
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(sql))
{
con.Open();
cmd.Connection = con;
cmd.Parameters.Add("@userid", System.Data.SqlDbType.Int).Value = userid;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
user.UserId = userid;
user.UserType = rdr["usertype"].ToString();
user.DateCreated = (DateTime)rdr["datecreated"];
user.Email = rdr["email"].ToString();
user.Name = rdr["name"].ToString();
user.Phone = rdr["phone"].ToString();
string type = rdr.GetString(0);
if (type == "agent")
{
Agent agent = user as Agent;
agent.Company = rdr["company"].ToString();
agent.CompanyReg = rdr["companyreg"].ToString();
agent.SecurityQuestion = rdr["securityQuestion"].ToString();
agent.SecurityAnswer = rdr["securityanswer"].ToString();
agent.Description = rdr["description"].ToString();
agent.AccountBalance = (int)rdr["accountbalance"];
agent.WantsRequests = Convert.ToBoolean(rdr["wantsrequests"]);
returnuser = agent;
}
else //type == "client"
{
Client client = user as Client;
client.Country = rdr["country"].ToString();
client.IP = rdr["ip"].ToString();
returnuser = client;
}
}
}
}
}
catch (SqlException e)
{
throw e;
}
return returnuser;
}
You can’t cast from a base class to a child class if you instantiate the object as the base class.
You are attempting to use
asto cast from aUserto aClientor anAgentdepending on your data. However, you are explicately creating aUserobject at the start of your function:This object is of type
Usersoaswill not be able to convert it to aClientor anAgentand will return null. See the documentation here.You can demonstrate this as follows:
What you need to do is to explicitly create the most specific class you need, either a new
AgentorClient, then cast this to a more genericUserwhen and as you need to.For example: