Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6200675
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T04:24:44+00:00 2026-05-24T04:24:44+00:00

I have a DB table with users, some are ‘agents’ and some are ‘clients’.

  • 0

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;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T04:24:45+00:00Added an answer on May 24, 2026 at 4:24 am

    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 as to cast from a User to a Client or an Agent depending on your data. However, you are explicately creating a User object at the start of your function:

    User user = new User();
    

    This object is of type User so as will not be able to convert it to a Client or an Agent and will return null. See the documentation here.

    The as operator is like a cast except that it yields null on conversion failure instead of raising an exception.

    You can demonstrate this as follows:

    User u = new User();
    System.Console.WriteLine("u is User: " + (u is User));
    System.Console.WriteLine("u is Agent: " + (u is Agent));
    System.Console.WriteLine("u is Client: " + (u is Client));
    // Should produce:
    // u is User: true
    // u is Agent: false
    // u is Client: false
    
    Agent a = new Agent();
    u = a;
    System.Console.WriteLine("u is User: " + (u is User));
    System.Console.WriteLine("u is Agent: " + (u is Agent));
    System.Console.WriteLine("u is Client: " + (u is Agent));
    // Should produce:
    // u is User: true
    // u is Agent: true
    // u is Client: false
    

    What you need to do is to explicitly create the most specific class you need, either a new Agent or Client, then cast this to a more generic User when and as you need to.

    For example:

    public User GetUser(int userid)
        {
            User user;
            string sql = "...";
            try
            {
                using (SqlConnection con = new SqlConnection(constr))
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    //.. Snip sql stuff ... //
    
                            string type = rdr.GetString(0);
                            if (type == "agent")
                            {
                                Agent agent = new 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"]);
                                user = agent;
                            }
                            else //type == "client"
                            {
                                Client client = new Client();
                                client.Country = rdr["country"].ToString();
                                client.IP = rdr["ip"].ToString();
                                user= client;
                            }
    
                            // Now do generic things
                            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();
    
                            return user;
                        }
                    }
                }
            }
            catch (SqlException e)
            {
                throw e;
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i have table called users , if i want to delete some user (User
I have a table containing data about some users. Many of them use our
I have a table that saves some account limits like users. For most rows
We have a table where it records the scores of users at some games.
I have a Users table, Events table, and a mapping of UserEvents. In some
I have a table Users, so some rows specially in field Full Name are
I have a table containing users... one way or another some users were doubled
I have a table of users, some of which have articles associated with them,
You have a website with a user base. You want to allow some users
I have a table called Users it contain some fields such as Id, ParentId,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.