c# stock object array in other array - c#

I do a shop on a game and I want get a specifically array compared with the clicked button.
I have an object like this:
public class DressItem
{
private string text;
public string Text{
set{this.text = value;}
get{return this.text;}
}
private string mat;
public string Mat{
set{this.mat = value;}
get{return this.mat;}
}
}
Then in my script I create 3 DressItem item and I fill it with data, but I want one reference DressItem (named partRef) take property of one of previous array:
private DressItem[] pants;
private DressItem[] body;
private DressItem[] head;
private DressItem[] partRef;
How can I put object pants with this property in partRef and access to pants property like pant.text ?
I tried to put the 3 Dressitem in an arraylist and take it after like this:
private ArrayList arrayPart = new ArrayList();
arrayPart.Add(head);
arrayPart.Add(body);
arrayPart.Add(pants);
partRef = arrayPart(0) as DressItem;
But I have this error:
Cannot implicitly convert type 'DressItem' to `DressItem[]'
I tested to use a list but i must do a mistake i add my items like this:
private List<DressItem> arrayPart = new List<DressItem>();
arrayPart.Add(head);
arrayPart.Add(body);
arrayPart.Add(pants);
But i have this error :
The best overloaded method match for System.Collections.Generic.List.Add(DressItem)' has some invalid arguments.

I found my error: I typed my list as List<DressItem> instead of List<DressItem[]>, and the same for partRef. This was just a stupid mistake.

Related

The JSON value could not be converted to Scraper.items[]

so I am trying to convert a JSON string to a list of objects that I made myself but for some reasons it keeps throwing me errors and after googling it I couldn't find my error.
Here is what throws the error. (I already tried using a list instead of an array and it still made an exception).
items[] items = JsonSerializer.Deserialize<items[]>(h.Content.ReadAsStringAsync().Result);
This is the exception I'm getting:
"The JSON value could not be converted to Scraper.items[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
Here is what my object item looks like looks like :
public Int64 id;
public string title;
public double price;
public string currency;
public string brand_title;
public string size_title;
public user user;
public bool is_for_swap;
public string url;
public bool promoted;
public photo photo;
public int favorit_count;
public bool is_favorite;
public string badge;
public string[] conversion;
public int view_count;
(I know I am not doing propreties or any constructor. I deleted them all while trying to solve my issue. (Other objects are also there but I wont show them since I don't think they are the thing making my exceptions and I don't want this post to be unreadable))
My JSON : https://pastebin.com/AZE1AwhL
Thanks for reading this and getting some help would make me progress a lot on my project.
The JSON you have linked is not an array. It's an object, with a property items which is an array. So JsonSerializer.Deserialize<items[]> won't work. You need to deserialize to a class with an items property.
Something like this:
public class Wrapper
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
// ...
var options = new JsonSerializerOptions { IncludeFields = true };
var wrapper = JsonSerializer.Deserialize<Wrapper>(
h.Content.ReadAsStringAsync().Result,
options);
wrapper.Items // This is your array
Side note: C# naming conventions dictate you should use PascalCasing for class names. So items should be called Items or more apropriately Item since it's not a list type.

How to add value to an array of object in C#

I am consuming a third party web service and I want to add value to match the service reference class, and i am not sure how to add value to the following:
in reference:
public partial class UserInfor: object, System.ComponentModel.INotifyPropertyChanged
{
private ABC[] listOfABCField;
public ABC[] ListOfABC
{
get {
return this.listOfABCField;
}
set {
this.listOfABCField = value;
this.RaisePropertyChanged("ListOfABC");
}
}
}
public partial class ABC : object, System.ComponentModel.INotifyPropertyChanged
{
private string ipField;
private string fristNameField;
private string lastNameField;
}
//////////////////////////////////////////////////////
in my service.asmx file have tried to put value as below:
in below code i got exception in line ABC[] abc=new ABC[0]; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC[] abc=new ABC[0];
abc[0].firstName= "petter";
abc[0].lastName = "lee";
user.ListOfABC = abc[1];
i also tried
in below code i got exception in line user.ListOfABC[0] = abc; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC abc=new ABC[0];
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC[0] = abc;
any idea how to add abc to user class ? thank you in advance
This'll probably be easier if you use a List<> instead of an array. Change the property:
private List<ABC> listOfABCField;
public List<ABC> ListOfABC
{
// etc.
}
Don't forget to initialize it in the class' constructor so it's not null:
public UserInfor()
{
listOfABCField = new List<ABC>();
}
Then you can just add an object to it, which doesn't need any of the array syntax you were trying to use:
UserInfor user = new UserInfor();
ABC abc = new ABC();
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC.Add(abc);
You are doing it wrong, first instantiate the array, if you know in advance how many items it would contain then specify that as well in the square brackets like:
ABC[] abc=new ABC[1]; // this array will contain 1 item maximum
now instantiate that item and then set values of properties :
abc[0] = new ABC(); // instantiating first item of array which is at 0th index
abc[0].firstName= "petter";
abc[0].lastName = "lee";
If you don't know how many item would come in it, then go with #David's suggestion of using List<T>

Useclasses without making new instances

I want to take a string in my mainpage and put it inside my class so I can get it in the next window. My Class is simple and looks like this:
name: Spreadsheet
private string itemType;
public string ItemType
{
get { return itemType; }
set { itemType = value; }
}
I can change it just fine if I make a new instance, but that will remove everything inside it - I don't want that. I Call the class using this line:
private Spreadsheet ss = new Spreadsheet();
When I call this method I make a new instance new Spreadsheet() which incorrectly puts all the strings into null. How can I avoid this?
Like Tyler Day said
I think you might be looking for the static keyword. – Tyler Day
That fixed my problems
making the private string itemType into private static string itemType was what I missed out :)
To explain why is that static fields are class-level variables that are per-type rather than per-instance

Updating a Struct property inside a Class

I know that a Struct is a value type and a Class is reference type, however I cannot seem to get around this issue.
I have a class that has a list of a struct:
public class Basket
{
string ID{get; set;}
List<Fruit> fruits{get;set;}
public struct Fruit
{
string Name{get;set;}
bool IsFresh;
}
}
when passing a class instance to another class I want to update one of the Structs' IsFresh property but the code just skips it:
public class Customer
{
public string Name{get;set;}
public Basket Basket{get;set;}
public Customer(string name, Basket basket)
{
this.Name = name;
this.Basket = basket;
}
public ChangeBasket()
{
//CODE THAT IS NOT WORKING
Basket.Fruits[0].IsFresh = false;
}
}
The same referenced class is being modified and the valued structs should be updated.
why is that not working?
You should not generally write mutable structs. Instead, assign a whole new struct. See here. Basically what's happening is that you're modifying a copy of your struct, as it is a value type.
First of all, you have some problems with access modifiers(use public when you want to access your code outside your class\structs).
Your problem is due to the reason that structs are value types, so when you access a list element you will access a copy of the element which has been returned by the indexer's "getter" of the list and not the list itself.
That means if you try to update the instance, the update will not really influence a change on the "real" entity, but on the copied one and that's why you get a compilation error.
This basket.Fruits[0].IsFresh = false;
should be:
Basket.fruits[0].IsFresh = false;
Does that fix it?
It seems you can't use the indexer when the list is a list of structs.
the following code works:
var x = Basket.Fruits[0];
x.IsFresh = false;

Make Global Method for DropDownList BInding

i am returning a list from a database like this;
ClsCampus campus = new ClsCampus();
List<ClsCampus> camp = campus.GetCampusAll();
Utility.BindComboBox(ComboBoxCampus, camp, "CampusName", "CampusId");
I have a class name Utillity, in which i have created a static method called BindComboBox.
public static void BindComboBox(DropDownList listName, List<Object> list,
string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
However, it gives me a compilation error.
So, How do i write a general purpose method where i can bind a generic list of records to a combobox
Error 1
The best overloaded method match for 'KenMISSchool.Repository.Utility.BindComboBox(System.Web.UI.WebControls.DropDownList, System.Collections.Generic.List<object>, string, string)' has some invalid arguments D:\Projects\KenMISSchool\Web\forms\student\registration.aspx.cs 20 9 Web
You are passing List<ClsCampus> but method expects List<Object> so I would change it to generic way:
public static void BindComboBox<T>(DropDownList listName, List<T> list, string textField, string valueField)
{
listName.DataTextField = textField;
listName.DataValueField = valueField;
listName.DataSource = list;
listName.DataBind();
}
and call it like this:
Utility.BindComboBox<ClsCampus>(ComboBoxCampus, camp, "CampusName", "CampusId");
We had a similar idea, but solved it in another way. I'm not sure if it will work for you, but here's a suggestion:
We implemented an Interface called IDropdownable (not the best name, I know), that forced two properties:
public string dropdown_value;
public string dropdown_text;
And we then implemented this interface over all classes that needed to be easily bound to dropdownlists:
public class Foo : IDropdownable
{
//Let's say these fields are already in the class:
private int _id;
private string _name;
private DateTime _date;
//The interface was then implemented:
public string dropdown_value
{
get
{
return this._id.ToString();
}
}
public string dropdown_text
{
get
{
return String.Format("{0} ({1})", this._name, this._date.Year);
//Or simpler: return this._name;
}
}
}
The only thing left was to create a generic function that takes in a IDropdownable parameter and outputs the dropdownlist the way you like it (HTML string, SelectList, List<SelectListItem>, ... many options there).
public List<SelectListItem> GenerateDDL(
List<IDropdownable> items,
string selected_value)
{ ... }
If you want I can give you an approximation of the function.
Comment
We did this in MVC2 ASP.Net 4. To be honest, I'm not sure what type should be returned in classic ASP.NET, but I assume some type of List/Array will work.

Categories

Resources