Reputation: 1
I have been using the c++ and new in c#. In c++ i use int a[8]
to declare an array and if the array is of an object we set the value by item[0].SetID(5)
which will set the value of first item's ID to 5. But i m unable to do it in c#.
namespace Arrays
{
class items {
public int ID { set; get; }
public string name { set; get; }
public items(int ID) {
this.ID = ID;
name = "Faizan";
}
}
class Program
{
static void Main(string[] args)
{
var i=new items[4];
i[0].ID=6;// this line is kind of c++ code but how I do it in c#
Random r = new Random();
for (int k = 0; k < 4; k++) {
i[k] = new items(r.Next());
}
foreach(items it in i){
Console.WriteLine("The item name {0} and the Id is {1}",it.name,it.ID);
}
}
}
}
Upvotes: 0
Views: 1691
Reputation: 1
IN c++ when we declare the array of an object it is automatically initialize to NULL or "0" and we can get or set the value just after that(correct me if i am wrong). What about the c#? What i think is that var i=new items[4]; this line initializes the array as well,does it?
Upvotes: 0
Reputation: 1109
Your item at index 0 is null. You need to do this instead
i[0] = new items{ID = 6};
Upvotes: 1
Reputation: 236218
Array will be filled with default values after creating. MSDN:
If you do not initialize an array at the time of declaration, the array members are automatically initialized to the default initial value for the array type.
For reference types (i.e. classes) default values are nulls. So you should initialize array items before accessing them:
var i =new items[4];
// i[0] here is null
for (int k = 0; k < 4; k++) {
i[k] = new items(r.Next()); // now i[0] points to object in memory
}
i[0].ID = 6;// now you can set object's property
Upvotes: 3
Reputation: 62246
i[0].ID=6;// this line is kind of c++ code but how I do it in c#
Your array at tha point is empty. You initialize it after in loop.
So
after access/changes properties of the instances inside that array
static void Main(string[] args)
{
Random r = new Random();
for (int k = 0; k < 4; k++) {
i[k] = new items(r.Next());
}
foreach(items it in i){
Console.WriteLine("The item name {0} and the Id is {1}",it.name,it.ID);
}
var i= items[4];
i.ID=6;// NOW YOU CAN ACCCESS IT
//OR SIMPLY
items[4].ID=6;
}
Upvotes: 0