Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,
I’m not sure why I’m getting a cast error. I can login as an Admin with no problem. I am using inheritance with customer class inheriting properties from user. A admin is just a normal user. Customer only has a few extra properties but before a lil earlier I was able to run my program no errors now all a sudden im getting this error. I’m so confused it came out of no where I thought maybe it’s a compiler error so I cleaned/rebuilt and still a error…..
C#
//LOGIN SCREEN AND WHERE THE ERROR OCCURS IN MY CATCH CLAUSE *** 			private void BtnLoginUser_Click(object sender, RoutedEventArgs e)    {
                try     {
                    loginUser = SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password.ToString());
                    if (txtUsername.Text == loginUser.Username && txtPassword.Password == loginUser.Password)   {
                        if (loginUser.IsAdmin == true){
                            Window showAdminSrc = new AdminWindow(loginUser);
                            showAdminSrc.Show();
                            Close();
                        }else if (loginUser.IsAdmin == false)   {
                            Customer CastUser = new Customer();
                                CastUser = (Customer)loginUser;
          Window nonAdmin = new CustomerScreen(CastUser);//((Customer)loginUser);
                            nonAdmin.Show();
                            Close();
                        }  else
                            lblInvalidText.Content = "Admin is not True or False!";
                    }
                    else  {
                        lblInvalidText.Visibility = Visibility.Visible;
                    }
                } catch(Exception ex)     {
                    ex.Message.ToString();
                    throw ex;
                }
            }
        }	//CUSTOMER SCREEN LOADING CONSTRUCTOR NOTHING SPECIAL..       		 public CustomerScreen(User user) {
            customerUser = (Customer)user;
            InitializeComponent();
            //Display Users 'username' on Src / *future - Data Binding.
            TxtBlockName.Text = "Hello:" + Environment.NewLine + customerUser.Username;
        }


What I have tried:

I have tried casting a few different ways.
I tried having it as I do in the Admin section because it works there.
This was working earlier but now with very few changes, I get this error. I DID NOT CHANGE ANYTHING IN THIS SECTION for getting this error.
Posted
Updated 7-Nov-18 19:47pm

1 solution

WE can't see the definitions of loginUser and user which are the only explicit casts in that code; we also can't see what type SQLuserAccess.UserLogin returns, or what is in user before you cast that.

So run your code in the debugger, and look at exactly what the variables contain.

At a guess, you say that Customer is derived from User but I'd suspect that UserLogin returns a member of the base User class, not a Customer - and you can't "up-cast" anything.
C#
public class User {}
public class Customer : User {}
...
Customer c;
User u = new Customer ();  // Fine, Customer derived from User.
c = (Customer) u;          // Also fine, u contains a Customer.
u = new User();
c = (Customer) u;          // Error because you can't upcast the User.
 
Share this answer
 
Comments
TheBigBearNow 8-Nov-18 2:23am    
Here is UserLogin
User class is just a class with Username password id property and customer just adds on a few properties like firstname etc..

I think i understand what you are getting at because Yes Login does return a User not a Customer i will try to figure it out otherwise.
In the debugger it gets the correct user and i put that user in the next screen and cast it into a customer i take a user object in CustomerScreen and in the constructor i cast that specific user object over to a Customer.
[code]
public static User UserLogin(string username, string password)
{
//SQL Login Query.
string SQLloginQuery = "SELECT * FROM Users WHERE Username=@username AND Password=@password";
SqlCommand cmdLogin = new SqlCommand(SQLloginQuery, connection);
cmdLogin.Parameters.AddWithValue("@username", username);
cmdLogin.Parameters.AddWithValue("@password", password);
try
{
connection.Open();
//int result = (int)cmdLogin.ExecuteScalar();
SqlDataReader reader = cmdLogin.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
User user = new User
{
UserID = Convert.ToInt32(reader["UserId"]),
Username = reader["Username"].ToString(),
Password = reader["Password"].ToString(),
IsAdmin = Convert.ToBoolean(reader["IsAdmin"]),
UserCreatedDate = Convert.ToDateTime(reader["UserCreatedDate"])
};
return user;
}
else
return null;
}
[/code]
Richard Deeming 9-Nov-18 9:15am    
TheBigBearNow 8-Nov-18 2:26am    
What do i do to upcast with
[code]c = (Customer) u;[/code]

because YES this is exactly what the issue is.
You have it dead on.
OriginalGriff 8-Nov-18 2:34am    
You can't upcast at all! Think about it - if you could do this:
public class A {}
public class B : A {public string s;}
...
A a = new A();
B b = (B) a;
Console.WriteLine(b.s);

Where does the string "s" come from? What does it contain? The system can;t magically create it, and the instance of A in the variable doesn;t have any space allocated for the string - so when you tried to print it's value you would be accessing memory that isn't allocated to the instance - and that could make your code crash in very interesting ways!
TheBigBearNow 8-Nov-18 2:42am    
Ok what would i do to fix this error?
In userlogin create another loginmethod one for Customer and keep mine for User or just return customer in loginmethod instead of user because my customer will inherit all the user properties and also have its own customer properties.
I tried code like this but then i get a nullreference error just like you said because no allocated memory here.
[code]
Customer CastUser = loginUser as Customer;
Window nonAdmin = new CustomerScreen(CastUser);
[/code]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900