vaso123
vaso123

Reputation: 12391

Variable is a type, which is not valid in the given context

I have an interface, called IUser

I have two models, User and Guest and both of them implements IUser

I have a class, called CardOut what has two properties, Card and User

Here is the constructor of the CardOut class:

public CardOut(Interfaces.IUser User, Card Card) {
    this.User = User;
    this.Card = Card;
}

I am getting out some rows from the database, and based on the type of a cell, I am creating a User or a Guest.

foreach (IDictionary<string, string> row in rows) {
    if (row["type"] == "xxx") {
        User UserValue = new User();
        UserValue.buildById(int.Parse(row["user_id"]));
    } else {
        Guest UserValue = new Guest();
        UserValue.buildById(int.Parse(row["id"]));
    }
    Card Card = new Card();
    Card.buildCardByIndex(int.Parse(row["cardindex"]));
    CardOut CardOut = new CardOut(UserValue, Card);  //Here is the error
}

When I want to instantiate a new CardOut object I am getting this error:

Error CS0103 The name 'UserValue' does not exist in the current context

How can I solve it? I can not create it outside of the if condition, because I do not know, what class should I instantiate.

Upvotes: 0

Views: 12935

Answers (1)

adjan
adjan

Reputation: 13652

Declare a variable of type IUser outside the if block, and instantiate it inside the if with the concrete type.

Edit: added a cast since IUser seems not to have a member buildById.

foreach (IDictionary<string, string> row in rows) {
    IUser UserValue;
    if (row["type"] == "xxx") {
        UserValue = new User();
        ((User)UserValue).buildById(int.Parse(row["user_id"]));
    } else {
        UserValue = new Guest();
        ((Guest)UserValue).buildById(int.Parse(row["id"]));
    }
    Card Card = new Card();
    Card.buildCardByIndex(int.Parse(row["cardindex"]));
    CardOut CardOut = new CardOut(UserValue, Card);  
}

Upvotes: 5

Related Questions