0

Hey I have a problem with my code. Sorry if the question is too easy but I can't find a solution.

I have an object called user in class 1

The Object User has this variables.

 public class User
{
    public string email { get; set; }
    public string password { get; set; }
    public string mobilenumber { get; set; }
    public string service { get; set; }
    public override string ToString()
    {
        return $"{email}: {password}: {mobilenumber}: {service}";
    }
}

These variables are filled with data in class 1

Now I want to access these data in class 2 and display them to me.

I tried something like

Class Firstclass{
    public void OnLogin(){
        public User user = new User();
        user.email = [email protected]
   }
}

Class B{
   protected override async Task OnInitializedAsync(){
    Firstclass firstclass = new Firstclass();
    string output = firstclass.user.email;
  }
}
2
  • The code you show in the second snippet won't fly outside of a method. You could put it inside Firstclass's Constructor for example. Commented Nov 14, 2022 at 11:30
  • it's quite odd to have the instance of User hardcoded like that in Firstclass.. anyway to make your desiderata something meaningful for the c# syntax, this would be an attempt: dotnetfiddle.net/CwGu90 Commented Nov 14, 2022 at 11:39

1 Answer 1

1

There are several ways to do that. A simple one would be to instantiate the User inside the constructor:

public Class Firstclass
{
    User user;        
    public FirstClass()
    {
       this.user = new User();
       this.user.email = "[email protected]";
       // more data could be here or use a local method to fill user's fields
    }
    public User 
    {
      get
      {
         return this.user;
      }
      set
      {
         this.user = value;
      }
    }
 }

Try to avoid using a public field, rather use a public property like User in above. Then in Class B, you would have:

Class B
{
    protected override async Task OnInitializedAsync()
    {
        Firstclass firstclass = new Firstclass();
        string output = firstclass.User.email;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.