I’m new to programming and I have the following problem.
I have a class with with an Array. However, I only know what size the array will have at a later point.
public class MyData
{
public double[] rad;
public void Integrate(int h_start, int h_stop, double dla_tar)
{
rad = new double[Math.Abs(h_stop - h_start)];
...fill up the rad array
}
--work with rad here--
}
How can I get the function Integrate to create the rad array in the MyData class. Like that it always stays null. This is probably a very dumb question…
The key is to call
Integratebefore usingrad. As long as you don’t useradin any way until you initialize it, you will be fine.Any field in a C# class automatically starts out as the default value for that type, which is 0 for a numeric type (
int,uint,long, etc.),falsefor abool, andnullfor any reference type, including arrays. The canonical way to solve this problem is to initialize the data from the constructor. So you could do something likeThis way, it’s impossible to use
radbefore it’s initialized.If you find that moving the initialization code to the constructor doesn’t make sense, you probably need to refactor into two classes so that each class has one job.