Scenario:
i have a web form from where i m taking input for Item class now i want to assign values to feature that have return type of list how can i do that.
item value = new item(),
value.feature = serialtextbox.text; //error
foreach ( var item in value) //error
{
item.SerialNo= serialtextbox.text;
}
Item and Item feature classes
Class Item
{
list<Itemfeature> features;
}
class ItemFeature
{
public int SerialNo
{
get { return serialno; }
set { serialno = value; }
}
public int Weight
{
get { return weight; }
set { weight = value; }
}
}
Plz help me out
Note: No language is specified, but it looks like C#. I’m assuming C# in this answer.
It’s not really clear what you’re trying to do here, but I’ll give it a shot. First of all, you’re going to want to post the actual code you’re using. This code won’t even compile, it’s loaded with syntax errors.
Let’s take a look at your objects first:
You have a custom class,
ItemFeature, which consists of a serial number (integer) and a weight (integer). You then have another custom class,Item, which consists of a list ofItemFeatures.Now it looks like you’re trying to add a new
ItemFeatureto theItemand then loop through all of them and set them again?. Something like this, perhaps?:(Note that this code is probably as free-hand as your code, so I haven’t tested it or anything.)
What I’ve changed here is:
Itemobject itself. TheItemobject contains a list as a property, but the object itself isn’t a list. You can loop through the property, not through the parent object.A few things to ask/note:
Itemclass has a public variable,features. This is generally frowned upon. It’s better to use a property. That way if you ever have to add logic behind it you won’t break compatibility outside of the object itself. TheItemFeatureclass has properties like this, which is good. They can be additionally shortened by using automatic properties if you’d like, just to keep things clean and simple.serialtextbox.Textvalue. It should be. I presented it in a simpler form as an introductory approach to something that will work under ideal conditions. But something like the following would be better:Edit: I just noticed that my call to
.Add()will actually fail. You’ll want to initialize the list before trying to use it. Consider changing theItemclass to something like this:Two things changed here:
null. So any call to.Add()or any other method on the list would throw aNullReferenceExceptionbecause there’s no object on which to call the method(s).