i have a list of structs : user_stocks = new List<stock_Str>();
the struct is defined:
public struct stock_Str
{
public String name;
public int quote ;
public int chenge;
public bool quote_a;
public bool chenge_a;
public int[] rate_alarm;
public int[] chenge_alarm;
}
when i add item to the list i do:
stock_Str str = new stock_Str();
str.name = tbStockName.Text;
str.chenge_a = false;
str.quote_a = false;
str.quote = 0;
str.chenge = 0;
str.chenge_alarm = new int[2];
str.rate_alarm = new int[2];
for (int i = 0; i < 2; i++)
{
str.rate_alarm[i] = 0;
str.chenge_alarm[i] = 0;
}
_mainApp.user_stocks.Add(str);
my problems:
when i try to change values of the list items(of type struct), it don't change them!
my two arrays of two int's always set to null!
how can i fix it?
However, since structs are value types that cannot be null , the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null .
It is not a pointer so it cannot be "null". It can be zerofilled but it doen't mean it is empty either, it only means its filled with zeros.
Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor.
In C# a struct is a 'value type', which can't be null.
a: that should not be a struct, at all
b: the "value" of a struct is never null; even Nullable<T>
's null
is a bit of a magic-trick with smoke, mirrors and misdirection
Re the problem;
1: yes, that is because structs have copy semantics; you have altered a copy - not the same one
2: probably the same thing
Here's a more appropriate implementation; I imagine it'll fix most of your problems:
public class Stock
{
public string Name {get;set;}
public int Quote {get;set;}
public int Chenge {get;set;}
public bool QuoteA {get;set;}
public bool ChengeA {get;set;}
public int[] RateAlarm {get;set;}
public int[] ChengeAlarm {get;set;}
}
I'm unclear what the intent of the last 2 is, but personally I would prefer a list if it is a dynamic collection, for example:
private List<int> rateAlarms;
public List<int> RateAlarms {
get { return rateAlarms ?? (rateAlarms = new List<int>()); }
}
A struct is a Value type so you never get a reference of it to do edits only the copy.
Also you should use a class here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With