aaarianme
aaarianme

Reputation: 282

Returning a parent class - Inheritance

I have a parent class

public class User
{
    public int UserKey { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

I also have the class below that inherits from User

public class MyInfo : User
{
     public string Name { get; set; }
}

I have a utility class that returns a type of User. However I want to use the same method for MyInfo and only fill out whatever MyInfo inherited from User. The method can be found below:

public static User fetchUserInformation()
{
    User user = new User()
    //fetch data..
    return user;
}

What I’m doing is

MyInfo myinfo = fetchUserInformation();

but this wouldn’t work since fetchUserInformation returns a type of User.

Upvotes: 0

Views: 503

Answers (2)

Yiyi You
Yiyi You

Reputation: 18179

You can try to serialize User and deserialize it to MyInfo.

Change

MyInfo myinfo = fetchUserInformation();

to

MyInfo myInfo = JsonConvert.DeserializeObject<MyInfo>(JsonConvert.SerializeObject(fetchUserInformation()));

Another way,you can try without using inheritance.Here is a demo:

public class MyInfo
    {
        public string name { get; set; }
        public User user { get; set; }

    }
MyInfo myInfo = new MyInfo { user = fetchUserInformation() };

Upvotes: 1

Pierre Michel
Pierre Michel

Reputation: 407

I think that is how you shoud do it:

    public class MyInfo : User
    {
        public string name { get; set; }

    }
    public class User
    {
        public int UserKey { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public void fetchUserInformation()
        {

            Username = "TOTO";

        }
    }


    MyInfo infos = new MyInfo();
    infos.fetchUserInformation();
    Console.WriteLine(infos.Username);

Otherwise I think you should do the new outside of the method. Because if you want a MyInfo object you need to do new MyInfo() so maybe pass the user as a parameter ?

Upvotes: 0

Related Questions