altaaf.hussein altaaf.hussein - 2 months ago 11 Question

Collections in C# over VB.NET

Hi I am new to C# and have been learning it. Actually think I am getting use to it there are a few things which I am unsure about but will try to research them before asking. That said one thing I cannot find it collections. I come from a VB.NET back ground and previously I used collections of another class to store its properties instead of having to wade through a datatable. My previous code was something like the following

Public class UserDetails

Public Property Username() As String
Return sUsername
End Get
Set(ByVal value As String)
sUsername = value
End Set
End Property

Public Property Forename() As String
Return sForename
End Get
Set(ByVal value As String)
sForename = value
End Set
End Property

Public Property Surname() As String
Return sSurname
End Get
Set(ByVal value As String)
sSurname = value
End Set
End Property

End Class

you get the idea, a class with properties for what ever reason (this is easy in c# and somthing I have managed to do).

public string Username { get { return sUsername; } set { sUsername = value; } }
public string Forename { get { return sForename; } set { sForename = value; } }
public string Surname { get { return sSurname; } set { sSurname = value; } }

Then I have another class and create an object to this class and store each object in a collection, again as below;

clUserDetails = New Collection
Dim objUserDetails as new UserDetails
objUserDetails.Username = "SomeonesUsername"
objUserDetails.Forename = "SomeonesForename"
objUserDetails.Surname = "SomeonesSurname"

and the class also have a function which returns the collection

Public Function Items() As Collection
Return clUserDetails
End Function

Now I retrieve this either by looping through each object and assigning an object to get to the properties or do the following


Now in C# I have tried to use List<> as I cannot find the collection object. I am assuming this is VB thing so would like some help as how to accomplish this in C#.

I have tried the following

private List <UserDetails> clUserDetails;
UserDetails objUserDetails = new UserDetails();
objUserDetails.Username = "Username";
objUserDetails.Forename = "Forename";
objUserDetails.Surname = "Surname";

but I am stuck as to how to get the single object of of this list/collection.

Can somebody help


Is this what you want to be able to do?

Your model:

public class UserDetails
    public string Username { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }

And create/add a user to a List<>

var userDetails = new UserDetails
    Username = "Username",
    Forename = "Forename",
    Surname = "Surname"
}; // object initialiser

var listOfUsers = new List<UserDetails>();

And then retrieve using an index (provided it exists), like so: