I am a new developer to c# MVC3. I have a problem that I cannot create object that contains arrays of property inside object.
For example, I want to create instance ABC.Property[] for 10 arrays.
ABC.Property[0]
ABC.Property[1]
ABC.Property[2] ..... .... ABC.Property[10]
I used debug mode to check and found out that ABC.Property[] is null. So i cannot add the value back to that object's array.
How to crate object with propeties's array?
thank you.
namespace finance3.Models
{
public class Expected_and_Risk
{
public decimal[] Prop { get; set; }
public decimal[] Forecast { get; set; }
public string[] Name { get; set; }
public decimal[] AxB { get; set; }
public decimal[] PowAxB { get; set; }
public decimal ExpectValue(Expected_and_Risk abc)
{
decimal count = abc.Forecast.Count();
Expected_and_Risk Result = new Expected_and_Risk();
for (int i = 0 ; i < count ; i++)
{
// here is the problem
// i cannot add new data to array because it has no dimemsion and i tried this
//
// Expected_and_Risk[] Result = new Expected_and_Risk[10];
//
// but it didn't work
Result.Name[i] = abc.Name[i];
Result.Prop[i] = abc.Prop[i];
Result.Forecast[i] = abc.Forecast[i];
Result.AxB[i] = abc.Prop[i] * abc.Forecast[i];
decimal a = Result.AxB[i];
decimal sumAxB =+ a;
double temp = (double)(a * a) ;
Result.PowAxB[i] = (decimal)(temp);
}
return Convert.ToDecimal(Result);
}
}
}
You need to add a Constructor in your class and in that constructor you can define the size for your property
Also read about object oriented programming, Also check out this article An Intro to Constructors in C#
Better way could be to add following method into Expected_and_Risk class and call it from within constructor.
EDIT - edit is done to make Initialize private, and call it within constructor.
After that use it in ExpectValue like
At the moment, you've got arrays within
Expected_and_Risk
, but you're never initializing the variables. You could do so within a constructor:... but I'd suggest that's actually a nasty design. Any time you have lots of collections, all with the same count, where
x[0]
corresponds toy[0]
andz[0]
etc, you should consider having one collection of a custom type representing the encapsulation of those properties. For example:... except that of course now
abc
would be an array too. (It's not clear whether you're really just trying to copy all the values here, or whether you've got some business logic involved. There are better ways of copying values.)Alternatively, if you really do want collections within
Expected_and_Risk
, you might want to consider usingList<T>
instead of arrays. That way you don't need to specify the count up-front.