c# - Collection as out parameter -
i'm new concept of collections. have class object (officer) has several attributes, 3 of form name of officer.
i have separate class object called company, heirarchially positioned above officer object. company contains selection of officers, display names of officers need form of reference between two:
private list<officer> officerlist; public void addofficer(officer off) { officerlist.add(off); } now, homecoming info class, need either create list (pointless), create big number of officer objects (inefficient), or homecoming collection.
public void getofficernames(out *something* names) //i want utilize collection //here... think { foreach (officer o in officerlist) { names = o.title + o.forename + o.surname; } } that's far i've got, i'm having difficulty understanding a) how implement collection and b) if it's right thing do.
you don't need out modify reference type passed function, suffice:
public void getofficernames(list<string> names) { foreach (officer o in officerlist) { names.add(o.title + o.forename + o.surname); } } also, more readable homecoming names:
public ienumerable<string> getofficernames() { homecoming officerlist.select(o => o.title + o.forename + o.surname); } then can utilize this:
var names = new list<string>(); //... names.addrange(getofficernames()); or just:
var names = getofficernames().tolist(); out used value types, make them beingness passed reference. may used reference types if need initialize them. so, in case illustration this:
public void getofficernames(out list<string> names) { names = new list<string>(); foreach (officer o in officerlist) { names.add(o.title + o.forename + o.surname); } } and used this:
list<string> officernames; // uninitialized getofficernames(out officernames); foreach (var name in officernames) // out guarantees officernames { // initialized here //... } this needed, not readable, , discouraged , used.
c# collections
No comments:
Post a Comment