
Question:
I'm not using this in a real app but I was just curious on how to do this (C#).
I set one record of sample data in the constructor :
public class MikesClass
{
public MikesClass()
{
Id = 01; Name = "Mike";
}
public int Id { get; set; }
public string Name { get; set; }
}
but I'm confused on how to set another record in it :
public MikesClass()
{
Id = 01; Name = "Mike";
Id = 02; Name = "Tom"; ???
}
If possible to do this, what is the syntax? thanks
Answer1:You completely misunderstood what a constructor is. A constructor is for one single object
. It creates one single object. Thus you cannot set another record with it. That record will be a different object. You just set the values as arguments to constructor when you create another record.
So, should at least be like this -
public class MikesClass
{
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}
and in some distance place when creating multiple records/objects -
var m1 = new MikesClass(0,"name1");
var m2 = new MikesClass(1, "name2");
Answer2:Using the code you specified above, each time you write:
MikesClass mc = new MikesClass();
you will get an object of type MikesClass
with the Id
property set to 1 and the Name
property set to "Mike". Since each instance of MikesClass represents a single object, you cannot have multiple objects represented within it.
What you can do though, is modify your constructor to take the two values as parameters. Like this:
public MikesClass(int id, string name)
{
Id = id;
Name = name;
}
You can then use this code to create multiple MikesClass
objects like so:
MikesClass mike = new MikesClass(1, "Mike");
MikesClass tom = new MikesClass(2, "Tom");
Hope this makes sense.
Answer3:What you're showing is a constructor. It is run when you create an instance of the MikeClass class. What you want is to create several instances. Maybe in an array?
MikeClass[] array = new MikeClass[2];
MikeClass mc = new MikeClass(); /first instance
mc.Id = 1;
mc.Name = "Mike";
array[0] = mc;
mc = new MikeClass(); //another instance
mc.Id = 2;
mc.Name = "Tom";
array[1] = mc;
};
This is using object initializer syntax:
MikeClass[] array = new MikeClass[] {
new MikeClass { Id = 1, Name = "Mike" }, //first instance
new MikeClass { Id = 2, Name = "Tom" } //another instance
};
You can also create a constructor for the MikeClass class that takes parameters:
public MikeClass(int id, string name) {
Id = id;
Name = name;
}
Then:
MikeClass[] array = new MikeClass[] {
new MikeClass(1, "Mike"),
new MikeClass(2, "Tom")
};