Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of structs - the value of the struct items is always null

Tags:

c#

.net

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:

  1. when i try to change values of the list items(of type struct), it don't change them!

  2. my two arrays of two int's always set to null!

how can i fix it?

like image 476
Michael A Avatar asked Feb 08 '11 08:02

Michael A


People also ask

Can struct have null values?

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 .

Can a struct be null in C++?

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.

Can a struct contain a list?

Yes you can have a list in struct but you cannot initialise it with a field initialiser and instead you must use the constructor.

Can struct be nullable?

In C# a struct is a 'value type', which can't be null.


2 Answers

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>()); }
    }
like image 108
Marc Gravell Avatar answered Oct 26 '22 23:10

Marc Gravell


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.

like image 43
Shekhar_Pro Avatar answered Oct 27 '22 00:10

Shekhar_Pro