Click here to Skip to main content
15,311,717 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing an ASP.NET API to display a list of users with their game scores. There are two classes: User, and Data.

class User
{
    public string name {get; set;}
    public int age {get; set; }
}


User data class:
class UserData
{
    public string id {get; set;}
    public int finalScore {get; set; }
    public int dateJoined {get; set; }
}


Now, I want to add it to my List view, but I am stuck here.

What I have tried:

I tried using this approach:
<pre>
List<User> userList = new List<User>{
            new User() { name="Ethan Hunt", age = 23, new UserData() { id="A3928", finalScore=938, dateJoined = "3/12/2013" } },
}


What is the proper way to do so?
Posted
Updated 21-Nov-21 21:20pm

1 solution

The problem is that your User class doesn't contain any UserData variables - so you can't "add" the information to it when you create the class instance.

Think of it like cars: if you want to put your mobile in the glovebox, you have to specify a car first: your car. Then open the glovebox which is part of your car, add your phone, close the glovebox, and then get out of youe car.
in software, that requires three classes:
C#
class Phone : ISmallItem {...}
class Glovebox
   {
   List<ISmallItem> Contents {get; set;} = new List<ISmallItem>();
   }
class Car
   {
   ...
   GloveBox GloveBox {get; set;} = new GloveBox();
   }
Now you can reference your car, open it's glovebox, insert your phone:
C#
myCar.GloveBox.Contents.Add(myPhone);

Make sense?

So in your example, you need to add a property or field to your User class, to hold teh UserData data:
C#
class User
    {
    public string Name {get; set;}
    public int Age {get; set; }
    public UserData UserData {getl; set;}
    }
Now your List code will work.

Please notice that I Uppercased yoru properties: that is a the standard for C#, all properties and methods start with an Uppercase letter to differentiate them in code from local variables. It's a good idea to stick with the naming conventions right from the start, as it's much easier to get into good habits than to break bad ones later!
   

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