How can I declare a two dimensional double array inside the structure?
public struct PROBABILTY_SETUP
{
double[,] probablity[2,9613];
}
The above code NOT WORKING...
Because you're in a struct, you'd have to make it static, as you can't have an initializer for a non-static struct member (another option is use a constructor however).
If it was a class however, the below would work without the static keyword.
Try this:
public struct PROBABILITY_SETUP
{
static double[,] probablity = new double[2, 9613];
}
If you require more than one however, consider using a constructor
public struct PROBABILTY_SETUP
{
double[,] probablity;
public PROBABILTY_SETUP(double [,] probability)
{
this.probablity = probability;
}
}
You'll have to call the constructor with the array you require:
PROBABILITY_SETUP mySetup = new PROBABILITY_SETUP(new double[2, 9613]);
Related
Here is my code and it gives red squiggly line under the variable of the array declaration, stating,
Fixed size buffer fields may only be members of struct
float is a value type, so I don't quite understand this message.
What is the correct syntax to create public array of 13 elements (0 through 12; I ignore index 0)...
class clsUtility
{
public int UtilityId { get; set; }
public fixed float InterpolationFactorMonth[13]; // <-- HERE IS THE PROBLEM
}
If you want a fixed-sized array inline, that has to be declared within a struct, as per the compiler error. If you're actually happy with a reference to an array as normal, you need to differentiate between declaration and initialization. For example:
// Note: Utility isn't a great name either, but definitely lose the "cls" prefix.
class Utility
{
public int UtilityId { get; set; }
public float[] InterpolationFactorMonth { get; } = new float[13];
}
This declares a read-only property of type float[], and initializes it with a new array of 13 elements.
So first of all, it is not possible to use fixed in this case.
You could use public float[] InterpolationFactorMonth = new float[13];
To create an array of the size 13.
I have a program written in C which contains some nested structures of arrays like the following:
typedef struct
{
int s1var1[s1max1],
float s1var2[s1max2];
}struct1;
typedef struct
{
int s2var1[s2max1];
struct1 s2var2[s2max2];
*s2var2_ptr;
}struct2;
and I've written it in C# as following:
class Class1
{
public int[] s1var1 = new int[s1max1];
public float[] s1var2 = new float[s1max2];
}
class Class2
{
public int[] s2var1 = new int[s2max1];
public Class1[] s2var2 = new Class1[s2max2];
}
Is my translation true? What is wrong with this translation?
Thanks for your time.
public struct struct1
{
public int[] s1var1;
public float[] s1var2;
}
public struct struct2
{
public int[] s2var1;
public struct1[] s2var2;
}
public static void Main()
{
struct1 str;
str.s1var1 = new int[10];
str.s1var2= new float[10];
//or
struct1 str1 = new struct1();
str1.s1var1 = new int[10];
str1.s1var2= new float[10];
////
struct2 str2;
str2.s2var1 = new int[10];
str2.s2var2 = new struct1[10];
}
A struct type is a value type that is typically used to encapsulate
small groups of related variables, such as the coordinates of a
rectangle or the characteristics of an item in an inventory.
When a struct is created, the variable to
which the struct is assigned holds the struct's actual data. When the
struct is assigned to a new variable, it is copied. The new variable
and the original variable therefore contain two separate copies of the
same data. Changes made to one copy do not affect the other copy.
Microsoft source
Learn More About Structs
Classes and Structs
First, let's take a look at your code conceptually. In C you have some structures and in C# you have some classes. You will need to know that struct is different from class in many ways, not to mention that we have here some different languages as well, so writing a C# struct would be more suitable. However, if we look at your implementation, we see that on declaration level you try to assign some values to your arrays respectively. Are you sure the limits you use are defined and visible at the point you attempt to use them? Also, it would be much better if you would use a constructor and initialize your arrays there. And finally, I'm not sure at the point of Class2 you see Class1 which you attempt to use.
I have a structure as below. I have few problems
Problem1:
struct MyStruct
{
public MyStruct(int a)
{
this.a = a;
this.b = 10;
}
public int a;
public int b;
}
When I remove this.b from MyStruct constuctor it will give me an error "Field must be fully assigned before control is returned to the caller". but in case of class it doesn't occur
Problem2:
struct MyStruct
{
//public MyStruct(int a)
//{
// this.a = a;
// this.b = 10;
//}
//int asd;
//public int MyProperty { get; set; }
public void getImplemen()
{
Console.WriteLine("azsdfa");
}
public int a;
public int b;
}
static void Main(string[] args)
{
MyStruct myStruct ;
myStruct.a = 15;//when I comment this it will give an error
myStruct.b = 15; //when I comment this it will give an error
myStruct.getImplemen();
}
When I change MyStruct myStruct to MyStruct myStruct = new MyStruct ();
it works fine.
why so?
That's just how it goes.
Default constructor initializes every field to a default value, while a constructor with parameters forces you to initialize every field in the struct.
What if you have a default constructor AND one with parameters, you ask? Well, I don't remember. Easy enough to check on your own.
It does not allocate memory for fields:
MyStruct myStruct;
Allocates memory and initialize fields in constructor:
MyStruct myStruct = new MyStruct();
If you does not allocate memory for a variable then you can not assign a value to the fields. Сonstructor allocate memory and initializes fields (you need initialize fields in constructor before control is returned to the caller).
you should refer to https://msdn.microsoft.com/en-us/library/aa288471(v=vs.71).aspx
you need to create the instance of your struct before using it.
The difference is that structs are value types while classes are reference types. When a value type object is created, memory space will be allocated to store the value, thus its member variable cannot be null, whilst class member variables can be null. Hence, the compiler only complains when struct member variables are not assigned to.
Remember the thumb rule for Structs: All fields must be initialized. Values can be provided by you or default ones.
For Question 1:
When you initialize struct with 'new' (without parameters), all fields in it are initialized to default type values (0 for int, null for string etc). Since you are using parameterized constructor compiler does not use default one and hence you get error if you don't initialize field 'b'. You can still make this work as below:
public MyStruct(int a) : this()
{
this.a = a;
}
For Question 2:
Recall the thumb rule I mentioned in the beginning. So you either use default constructor with 'new' initialization or set field values in calling code.
Quick suggestion: Please do not use public fields in class/struct. Use properties to encapsulate them.
Consider this code:
MyStruct j;
j.I = 3;
Console.WriteLine(j.I);
Now see this method:
public static void StructMod(MyStruct ms)
{
ms.I += 100;
Console.WriteLine(ms.I);
}
When we pass MyStruct to the method, should we initialize it before passing it? I.e.:
MyStruct j = new MyStruct()
Unless struct is value type?
Yes, it is.
First line from MSDN:
A struct type is a value type...
As with individual variables, a struct must be fully initialized before it can be used. Consider:
struct Foo
{
public int Bar;
public int Pop;
}
class Program
{
static void Main(string[] args) {
Foo f;
f.Bar = 3;
test(f); // ERROR: Use of unassigned local variable 'f'
}
static void test(Foo f) {
Console.WriteLine("{0}", f.Bar);
}
}
The solution here is to either initialize .Bar, or simply call the Foo constructor f = new Foo() which initializes all members to their default values.
This is the same logic behind the "Field ... must be fully assigned before control is returned to the caller" error that you get when adding parameterized constructors to structs.
After a little testing, it seems that either way you declare it, it's being initialized.
One reason to call new ... would be to execute code in the constructor, if any.
Take this sample from MSDN, for example:
public struct CoOrds
{
public int x, y;
public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
You could just do this, and use c, but then x and y will be 0.
CoOrds c;
Alternatively, you could do this, and then x and y start off with values.
CoOrds c = new CoOrds(5,3);
(This would be more useful if the ctor did something more interesting.)
If you want the struct to have a particular value, then initialize it to that value.
If you want the struct to be initialized to its default value, then you don't need to explicitly initialize it. However, it might still be best to do so for the sake of readability if the struct's default value is non-obvious.
As a side note: Mutable structs are really bad; the entire scenario you propose in your example is a code smell. See Why are mutable structs “evil”?
The same behavior could be achieved more safely with an immutable struct like so
struct MyStruct
{
public readonly int I;
public MyStruct(int i_initial)
{
I = i_initial;
}
}
MyStruct j = new MyStruct(3);
public static void StructMod(MyStruct ms)
{
Console.WriteLine(ms.I + 100);
}
In particular, note that from the caller's point of view this function's behavior will be exactly the same as the one in the question, because structs are passed by value the same way that primitives like int are. If the "Mod" in StructMod is there because you expect this function to modify the value, then that's a good concrete example of why it's generally better for mutable types to be objects and not structs.
I need help about array of structs initiliazation. In a code something like below, how we can accomplish the initiliazation defined in comment ??
class structExample
{
struct state{
int previousState;
int currentState;
}
static state[] durum;
public static void main(String[] args)
{
durum = new state[5];
// how we can assign new value to durum[0].previousState = 0; doesn't work ??
}
}
}
Thanks..
The default accessibility for members in C# is private which is why the assignment statement is failing. You need to make the fields accessible by having adding internal or public to them.
struct state{
internal int previousState;
internal int currentState;
}
durum = new state[5]; -> creates only the array for 5 elements.
You need to initialize every element inside the array.