Struggling with generic function

Solarion

Honorary Master
Joined
Nov 14, 2012
Messages
28,050
Reaction score
17,804
I am trying to create a method that can take in any list<T> then insert this row into that list, and return it. This is using a Student class for example:

students.Insert(0, new Student() { Name = "Please Select" });

I will then use that list to bind to a combobox. The reason for this is that at any time I need to populate a combobox I will always have the following as the first item: "Please Select"

This is about as far as I've gotten. The "YourDerived" is where the steam train left the track and ended up down into a ravine and disappeared under water in a plume of white steam and a trail of destroyed trees in it's wake.

C#:
public List<T> AddItem<T>(List<T> collection)
{
   collection.Insert(0, new YourDerived { Id = 0, Name = "Please Select" });
   return collection;
}

Please if you guys have any suggestions I would very much appreciate it!

Edit: This is not work related but something I am hoping to use in future.
 
Haven't touched c# in years, but the "Please select" item is basically a placeholder and not an actual item in the list (ie. not a student)

You should force yourself to think about the use and responsibility of data and the part of the system using it, "concerns" if you will. It's difficult to explain but maybe if you look at each part of your system as a subsystem that can "live on it's own" it starts making more sense.

For example, that list of students is probably derived from a database of some sort and if you're looking at your classic N-Tier architecture it is created by your DAL/Data Access Layer, requested by your Business Layer and displayed by your UI layer.

The DAL knows not what this data will be used for. It may be displayed on the UI, used as part of a report, used in an API etc. It's responsible for getting data and supplying it to the requester and that's where it ends.

The "Please Select" placeholder is very much a UI thing so what this very long winded post is actually saying is that you shouldn't be adding it to the collection. Apart from it just feeling wrong, you don't know what order the UI is going to display these items in. What if there is an order button added one day to sort the collection from Z-A, "Please Select" will end up between "Percy" and "Susan".

And now for the TL;DR part:
Why not add the placeholder directly to the combobox or make use of a placeholder property if there is one?
 
For example, that list of students is probably derived from a database of some sort and if you're looking at your classic N-Tier architecture it is created by your DAL/Data Access Layer, requested by your Business Layer and displayed by your UI layer.

That is pretty much exactly what is going on here. Also yes it does not feel right at all adding other items to the List, I was on a train of thought and just ran with it.

I think the problem I'm having is that once a combobox is databound it is forbidden from adding items to, but you've given me something to think about and dig around more. I'll post back here what I find.
 
 
Think you might be looking for the PlaceholderText property (if this is XAML)
 
Haven't touched c# in years, but the "Please select" item is basically a placeholder and not an actual item in the list (ie. not a student)

You should force yourself to think about the use and responsibility of data and the part of the system using it, "concerns" if you will. It's difficult to explain but maybe if you look at each part of your system as a subsystem that can "live on it's own" it starts making more sense.

For example, that list of students is probably derived from a database of some sort and if you're looking at your classic N-Tier architecture it is created by your DAL/Data Access Layer, requested by your Business Layer and displayed by your UI layer.

The DAL knows not what this data will be used for. It may be displayed on the UI, used as part of a report, used in an API etc. It's responsible for getting data and supplying it to the requester and that's where it ends.

The "Please Select" placeholder is very much a UI thing so what this very long winded post is actually saying is that you shouldn't be adding it to the collection. Apart from it just feeling wrong, you don't know what order the UI is going to display these items in. What if there is an order button added one day to sort the collection from Z-A, "Please Select" will end up between "Percy" and "Susan".

And now for the TL;DR part:
Why not add the placeholder directly to the combobox or make use of a placeholder property if there is one?

Nicely said, definitely best handled on the actual control level.
 
Haven't touched c# in years, but the "Please select" item is basically a placeholder and not an actual item in the list (ie. not a student)

You should force yourself to think about the use and responsibility of data and the part of the system using it, "concerns" if you will. It's difficult to explain but maybe if you look at each part of your system as a subsystem that can "live on it's own" it starts making more sense.

For example, that list of students is probably derived from a database of some sort and if you're looking at your classic N-Tier architecture it is created by your DAL/Data Access Layer, requested by your Business Layer and displayed by your UI layer.

The DAL knows not what this data will be used for. It may be displayed on the UI, used as part of a report, used in an API etc. It's responsible for getting data and supplying it to the requester and that's where it ends.

The "Please Select" placeholder is very much a UI thing so what this very long winded post is actually saying is that you shouldn't be adding it to the collection. Apart from it just feeling wrong, you don't know what order the UI is going to display these items in. What if there is an order button added one day to sort the collection from Z-A, "Please Select" will end up between "Percy" and "Susan".

And now for the TL;DR part:
Why not add the placeholder directly to the combobox or make use of a placeholder property if there is one?
I'm always curious what the actual file structure approach is with DAL/BAC/UI approaches (assuming it's different than MVC?)
 
I'm always curious what the actual file structure approach is with DAL/BAC/UI approaches (assuming it's different than MVC?)

Its just an older pattern, similar seperation logic though. DAL talks to your DB and structures, BAC ( your business layer I assume, not too familiar with that acronym, we just used BL ) for any rules in modifying or altering the data prior to presentation, UI being UI.

DAL's are quite typically structured around your database structure with a broker and sub classes.
 
I'm always curious what the actual file structure approach is with DAL/BAC/UI approaches (assuming it's different than MVC?)

It's actually not so straight forward. N-Tier is separating your code base into silos and the rules that govern how those layers interact with each other. The classic 3-Tier basically says that the UI and Data Layer must communicate with each other via the Business Layer:

Code:
UI <--> Business <--> Data Access

In the above case, your file structure shouldn't be that much different. Have a package, module, library, directory or whatever your language calls it for each layer. The way you choose to govern the comms between these layers and what each layer does will affect the internal layout of each parent package (interfaces, dependency injection, factories).

Depending on how you look at it though you can argue that MVC is another form or niche evolution of N-Tier. On the other hand your N-Tier architecture could involve multiple services and not a single application.

Code:
[  MVC ]     [                 N-Tier                ]
Angular <--> API  <--> Business Logic <--> Data Access

What about
Code:
[                     N-Tier                    ]
[ MVC ]      [  N-Tier  ]              [ N-Tier ]
                                  <--> Service
Angular <--> Unified API <--> Bus <--> Service
                                  <--> Service

To me N-Tier just means common sense. A name for a rationally designed system. Don't quote that in an interview though, use the 3-Tier example, that's the interview answer.
 
I may be mistaken but the "Text" property of a ComboBox sets an initial label. Is that what you are looking for? The displayed text is not added to any list.
 
It's actually not so straight forward. N-Tier is separating your code base into silos and the rules that govern how those layers interact with each other. The classic 3-Tier basically says that the UI and Data Layer must communicate with each other via the Business Layer:

Code:
UI <--> Business <--> Data Access

In the above case, your file structure shouldn't be that much different. Have a package, module, library, directory or whatever your language calls it for each layer. The way you choose to govern the comms between these layers and what each layer does will affect the internal layout of each parent package (interfaces, dependency injection, factories).

Depending on how you look at it though you can argue that MVC is another form or niche evolution of N-Tier. On the other hand your N-Tier architecture could involve multiple services and not a single application.

Code:
[  MVC ]     [                 N-Tier                ]
Angular <--> API  <--> Business Logic <--> Data Access

What about
Code:
[                     N-Tier                    ]
[ MVC ]      [  N-Tier  ]              [ N-Tier ]
                                  <--> Service
Angular <--> Unified API <--> Bus <--> Service
                                  <--> Service

To me N-Tier just means common sense. A name for a rationally designed system. Don't quote that in an interview though, use the 3-Tier example, that's the interview answer.
If an interview can't understand a flexible n-tier structure, I'd question my choices. Folks must remember, an interview is both ways, especially more senior you get.
 
There is no correct folder structure.

you can separate by “type” or by “domain” or by both.

by type (folders):

Code:
Services
   ...
   ...
Repositories
   ...
   ...
Models
   ...
   ...
etc

by domain (folders):

Code:
Customer
   CustomerServices (This customer “namespace/context name” in the file/class name might be optional as you are already in the Customer namespace/folder  )
   CustomerRepository
   CustomerModel

Orders
   OrderServices
   OrderRepository
   OrderModel

Or combine them.

In MVC, the Model is basically everything to the right of the controller (DTO’s, service/business layer, DAL)
 
I may be mistaken but the "Text" property of a ComboBox sets an initial label. Is that what you are looking for? The displayed text is not added to any list.

The text of the combobox is basically just that, text, however sitting below that text is a unique identifier aka StudentNo or some other value.

What happens with databinding a combobox is although it displays all the items, I've not found a clean way to select ALL the items: "Please Select"

Adding it before, and the databinding simply removes all your modifications. Adding it after and you get "The compiler gives this error: "Items collection cannot be modified when the DataSource property is set." "

Apart from Roi's suggested linke (connecting the combobox to a tableAdapter) and judging by what I've researched on stackoverflow, codeproject etc, nobody else knows how to do this either.

I really hate working with TableAdapters. Just rubs me up the wrong.

Edit: It's not a big issue this, just a little bugbear whenever it comes to working with selection boxes.
 
Last edited:
The text of the combobox is basically just that, text, however sitting below that text is a unique identifier aka StudentNo or some other value.

What happens with databinding a combobox is although it displays all the items, I've not found a clean way to select ALL the items: "Please Select"

Adding it before, and the databinding simply removes all your modifications. Adding it after and you get "The compiler gives this error: "Items collection cannot be modified when the DataSource property is set." "

Apart from Roi's suggested linke (connecting the combobox to a tableAdapter) and judging by what I've researched on stackoverflow, codeproject etc, nobody else knows how to do this either.

I really hate working with TableAdapters. Just rubs me up the wrong.

Edit: It's not a big issue this, just a little bugbear whenever it comes to working with selection boxes.

Ah, "Please Select" is normally something used when you want to force validation and selecting an option vs having an un-selected or default value. "All", should be an option in your dataset, either handled in code or database ( store procedure etc ). Which are you actually trying to do?

Also nothing stopping you from declaring an item in your designer ( winforms ) or html and then setting the property on the control "Append Databound Items"=true. Very old school way of doing it though.
 
I am trying to create a method that can take in any list<T> then insert this row into that list, and return it. This is using a Student class for example:



I will then use that list to bind to a combobox. The reason for this is that at any time I need to populate a combobox I will always have the following as the first item: "Please Select"

This is about as far as I've gotten. The "YourDerived" is where the steam train left the track and ended up down into a ravine and disappeared under water in a plume of white steam and a trail of destroyed trees in it's wake.

C#:
public List<T> AddItem<T>(List<T> collection)
{
   collection.Insert(0, new YourDerived { Id = 0, Name = "Please Select" });
   return collection;
}

Please if you guys have any suggestions I would very much appreciate it!

Edit: This is not work related but something I am hoping to use in future.

As others have said, rather use the built in functionality to do what you want.
Although, if you wanted to do something exactly like that, you need to use reflection.

C#:
   public List<T> AddItem<T>(List<T> collection)
        {
            Type type = typeof(T);

            if(!type.GetProperties().Any(x => x.Name == "Name" && x.CanWrite == true))
            {
                throw new Exception("Generic object must have a writable Name property.");
            }

            dynamic temp = (dynamic)Activator.CreateInstance(type);
            temp.Name = "Please select";

            collection.Insert(0, (T)temp);

            return collection;
        }

Or you could just use a base class which every class that can be in the list should implement.

C#:
    public class NamedObj
    {
        public string Name { get; set; }
    }

    public class Student : NamedObj
    {
        // rest of stuff here
    }
.....
    static void Main(string[] args)
    {
        List<Student> list = new List<Student>();
        list = AddItem(list);

        Console.WriteLine(list[0].Name);
    }

    static public List<NamedObj> AddItem(List<NamedObj> collection)
    {
        collection.Insert(0, new NamedObj() { Name = "Please Select");
        return collection;
    }
 
Last edited:
Thank-you so much Barbarian! I suspected I needed reflection but my knowleadge of how to use it is still beginner level. That's perfect :thumbsup::thumbsup::thumbsup:
 
Top
Sign up to the MyBroadband newsletter
X