How to declare an array of structs inside a struct? - c#

Using Visual Studios 2010 C#
so i am making a struct of data for a c# project, that will among it's members include an array of type another struct. So for example here is a stripped down idea of my code:
private struct scores
{
public double finalScore;
};
private struct information
{
public string name;
public scores[] scoreList;
};
I am getting the following warning when I write this:
Error 1 'WindowsFormsApplication1.main.information.scoreList': cannot
have instance field initializers in structs
I am wondering what is the correct way to declare the scores[] scoreList aspect of the struct information, so I can have the array size set to 10?
Things I have tried:
If I try
public scores[] scoreList = new scores[10]
I get the following error
Error 1 'WindowsFormsApplication1.main.information.scoreList': cannot
have instance field initializers in structs

In structs you can do initialization within constructors only:
struct information {
public string name;
public scores[] scoreList;
// Constructor
public information(String nameValue) {
name = nameValue;
scoreList = new scores[10]; // <- It's possible here
}
};

The problem here is that you're making the structs private, which means you can't make instances of them. Make them public. And also get rid of the ; at the end
public struct scores
{
public double finalScore;
}
public struct information
{
public string name;
public scores[] scoreList;
}
I typically don't use structs because of their OO limitations and the fact that they're not nullable. There are however several structs in .Net : DateTime, int, float etc...

You can't do this. The reason is that structs are value types. The default constructor of a struct is a parameterless constructor that initializes all fields to their default value. You don't have control over this constructor because they are value types.
The best way to show this is e.g. through an array. Say you make an array of a a class type, e.g. new object[10]. The items of this array will be initialized to null. However, when you would make an array of structs, e.g. new information[10], the items of the array will be valid instances already. However, the constructor on these items won't have run and all fields will have been initialized to their empty values. In your case, this means that all fields will be null.
There are two solutions to this. The first solution is to create a factory method, e.g.:
public static information CreateNew()
{
var result = new information();
result.scoreList = new scores[10];
return result;
}
This will work. You just create an instance with information.CreateNew() instead of new information(), and you will have an initialized information. However, a far more easy solution will be to just use a class instead.

There are three ways to have a structure behave as a value-type array of structs:
Use unsafe code to include one or more fixed arrays of primitives within your structure; have your indexed get/put accessors assemble a structure out of information stored in those arrays. For example, if you wanted to behave like an array of Point, one could have a fixed array for all the X coordinates and a fixed array for all the Y coordinates, and then have the this[int] getter construct a Point by combining an X and Y value, and the this[int] setter store the X and Y values from the passed-in point.
Have multiple fields of your struct type, and have the this[int] getter read from one of them and have the this[int] setter write to one of them. There are ways by which this can be made not too horribly inefficient, but it's still rather icky.
Have the structure hold a private array of the appropriate structure type. The get and set accessors should look something like:
T[] _array;
T this[int index] {
get {
T[] temp_array = _array;
if (temp_array == null) return default(T);
return temp_array[index];
}
set {
do
{
T[] was_array[] = _array;
T[] new_array = (temp_array == null) ? new T[size] : (T[])(temp_array.Clone());
temp_array[index] = value;
} while (System.Threading.Interlocked.CompareExchange(ref _array, new_array, was_array) !=
was_array);
}};
This approach will allow the get indexer to run faster than would be possible with the second approach (and probably the first as well), and unlike the first approach it will work with generic types. The primary weakness with this approach is that every time its set accessor is run it must make a new copy of the array. If writes are much less frequent than reads, however, that might not be a problem. Incidentally, as written, the code should be fully thread-safe--something which is possible with mutable structures, but not possible with structures that pretend to be immutable.

Related

Readonly property set code repeated in several constructor

I have a DataStructure class, which I want to be immutable.
Ordinarily, I'd just ensure that all my members are defined as readonly - Job Done.
But one of the members is a list (of ints), so I need to ensure that the List can't be modified; so I change it to a ReadOnlyCollection<T>. Fine.
I also need that collection to be ordered in a certain way - again fine, I sort the list accordingly before converting it via .AsReadOnly().
So far, it's all been fine.
But the last step is that I want 3 different constructors - each accepting the original data in a different format.
Now I have to duplicate the code that converts the list to the necessary format, in each constructor.
If I commonise it out into a setList() method, then the variable can't be readonly, because it's being assigned in a non-constructor method. Now I've lost some of the immutability.
Ideally, there would be some way that I can declare that the setList method can only be called from a constructor, and thus is allowed to edit readonly members, but I don't think that exists.
I could create wrap everything in getters and so forth, so that the class is immutable from the outside, but I'd rather like it to be immutable from the inside too (especially given that I can achieve this is I sacrifice DRYness)
Does anyone have any clever ideas about language features I've forgotten about that would solve this?
Rather than using a void SetList(List) called from constructors, you could have a List PrepareList(List). This method would prepare the list, and return it to the callers -ie: the constructors.
So the code wouldn't be repeated -except an affectation _list = PrepareList(list) in each constructors.
You can keep it as a normal list inside your class, but only expose it as readonly to the outside (just return .AsReadOnly() in a property).
Though if you definetely want the internal immutability, constructors can call each other:
public Foo( int a ) { ... }
public Foo( string a ) : this( int.Parse( a ) ) { ... }
So you can have most of the code in one constructor (even a private one if needed), and have the converting done in the others. Edit: it is a bit difficult to do alot of work that way, so I still think you should move the conversion out into methods. If the method doesn't access any class members, it'd still be internally immutable.
Another pattern I personally prefer (even if it's just syntactically different) is:
private Foo( int a ) { ... }
public static Foo FromBar( Bar b )
{
int x;
// convert from Bar here
return new Foo( x );
}
public static Foo FromSomethingElse( SomeThingElse b )
{
int x;
// convert from SomeThingElse here
return new Foo( x );
}

Best way to use Value types as Reference types?

I've been using something similar to this whenever I needed to reference a Value type:
public class RefHost<T> {
public RefHost(T val)
{
Value = val;
}
private T _value;
public T Value {
get {
return _value;
}
set {
_value = value;
}
}
}
What I'm wondering is there a built in way or an easier way to use an existing Value type as a Reference type?
Example:
public class Editor {
public RefHost<int> Blah = new RefHost<int>(5);
// Some kind of timer to increase the value of Blah every few ticks
}
Kind of like that where the user of Editor specifies a value type that needs to be changed, and there can be multiple instances of Editor each with it's own value. I used the timer as an example but most of the time it's a user control like a slider.
I think you are looking for Tuple.
Sure there is. If you want to pass it as a reference type to a method just use the ref modifier:
public static void Main()
{
int n = 1;
Test(ref n);
Console.WriteLine(n); //will print out 2 and not 1.
Console.ReadKey(true);
}
public static void Test(ref int x)
{
x = 2;
}
What's wrong with this?
public class Editor {
public int Blah = 5;
// Some kind of timer, with a handler like:
void MyTimerTicker(object sender, EventArgs e)
{
this.Blah += 1;
}
}
Boxing and unboxing is what this is called. Your solution might be more type safe though.
See http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
Replace the property and backing field with a public field. While it is generally good for classes to use properties rather than fields, the whole purpose of your type is to be a simple mutable container for a single value-type instance; the state encapsulated by any reference to an instance of the type should be precisely defined by two things:
The value of the `Value` member
The whereabouts of all other references to the instance that exist anywhere in the universe
If two instances have the same Value, and if within the entire universe only one reference exists to each one, the two references should be semantically indistinguishable [since in both cases the set of "other references" that exist to the instances would be empty]
While there are various helper methods that a type of that style might implement, it would be impossible for a future version of the type to add additional state without violating the expected semantics. Since the whole purpose of the type is to behave like a class object containing a single field of type T, code will be clearest if one writes the object to in fact be a class object containing a single field of type T.
BTW, if you don't want to define a custom type, another option is to use a single-element T[1]. That will use a little bit of extra storage to hold the dimension, and adding [0] to all references will be a little uglier than .Value, but such an approach will nonetheless work pretty simply.

C# - Calling a struct constructor that has all defaulted parameters

I ran into this issue today when creating a struct to hold a bunch of data. Here is an example:
public struct ExampleStruct
{
public int Value { get; private set; }
public ExampleStruct(int value = 1)
: this()
{
Value = value;
}
}
Looks fine and dandy. The problem is when I try to use this constructor without specifying a value and desiring to use the defaulted value of 1 for the parameter:
private static void Main(string[] args)
{
ExampleStruct example1 = new ExampleStruct();
Console.WriteLine(example1.Value);
}
This code outputs 0 and does not output 1. The reason is that all structs have public parameter-less constructors. So, like how I'm calling this() my explicit constructor, in Main, that same thing occurs where new ExampleStruct() is actually calling ExampleStruct() but not calling ExampleStruct(int value = 1). Since it does that, it uses int's default value of 0 as Value.
To make matters worse, my actual code is checking to see that int value = 1 parameter is within a valid range within the constructor. Add this to the ExampleStruct(int value = 1) constructor above:
if(value < 1 || value > 3)
{
throw new ArgumentException("Value is out of range");
}
So, as it stands right now, the default constructor actually created an object that is invalid in the context I need it for. Anyone know how I can either:
A. Call the ExampleStruct(int value = 1) constructor.
B. Modify how the default values are populated for the ExampleStruct() constructor.
C. Some other suggestion/option.
Also, I am aware that I could use a field like this instead of my Value property:
public readonly int Value;
But my philosophy is to use fields privately unless they are const or static.
Lastly, the reason I'm using a struct instead of a class is because this is simply an object to hold non-mutable data, should be fully populated when it is constructed, and when passed as a parameter, should not be able to be null (since it is passed by value as a struct), which is what struct's are designed for.
Actually, MSDN has some good guidance on struct
Consider defining a structure instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
Do not define a structure unless the type has all of the following
characteristics:
It logically represents a single value, similar to primitive types
(integer, double, and so on).
It has an instance size smaller than 16 bytes.
It is immutable.
It will not have to be boxed frequently.
Notice that they are considerations for considering a struct, and its never a "this should always be a struct". That is because the choice to use a struct can have performance and usage implications (both positive and negative) and should be chosen carefully.
Notice in particular that they don't recommend struct for things > 16 bytes (then the cost of copying becomes more expensive than copying a reference).
Now, for your case, there is really no good way to do this other than to create a factory to generate a struct for you in a default state or to do some sort of trick in your property to fool it into initializing on first use.
Remember, a struct is supposed to work such that new X() == default(X), that is, a newly constructed struct will contain the default values for all fields of that struct. This is pretty evident, since C# will not let you define a parameterless constructor for a struct, though it is curious that they allow all arguments to be defaulted without a warning.
Thus, I'd actually suggest you stick with a class and make it immutable and just check for null on the methods that it gets passed to.
public class ExampleClass
{
// have property expose the "default" if not yet set
public int Value { get; private set; }
// remove default, doesn't work
public ExampleStruct(int value)
{
Value = value;
}
}
However, if you absolutely must have a struct for other reasons - but please consider the costs of struct such as copy-casts, etc - you could do this:
public struct ExampleStruct
{
private int? _value;
// have property expose the "default" if not yet set
public int Value
{
get { return _value ?? 1; }
}
// remove default, doesn't work
public ExampleStruct(int value)
: this()
{
_value = value;
}
}
Notice that by default, the Nullable<int> will be null (that is, HasValue == false), thus if this is true, we didn't set it yet, and can use the null-coalescing operator to return our default of 1 instead. If we did set it in the constructor, it will be non-null and take that value instead...
I don't think it's good design to have a struct ExampleStruct such that
default(ExampleStruct)
i.e. the value where all instance fields are zero/false/null, is not a valid value of the struct. And as you know, when you say
new ExampleStruct()
that's exactly the same as default(ExampleStruct) and gives you the value of your struct where all fields (including "generated" fields from auto-properties) are zero.
Maybe you could do this:
public struct ExampleStruct
{
readonly int valueMinusOne;
public int Value { get { return valueMinusOne + 1; } }
public ExampleStruct(int value)
{
valueMinusOne = value - 1;
}
}
I guess the compiler is actually picking the automatic default ctor for structs here http://msdn.microsoft.com/en-us/library/aa288208(v=vs.71).aspx, rather than using your ctor with the default values.
added references:
http://csharpindepth.com/Articles/General/Overloading.aspx (Optional parameters section)
Although some languages (CIL if nothing else) will allow one to define a struct constructor such that new T() has fields set to something other than their "all zeroes" defaults, C# and vb.net (and probably most other languages) take the view that since things like array elements and class fields must always be initialized to default(T), and since having them be initialized to something which didn't match new T() would be confusing, structures shouldn't define new T() to mean something other than default(T).
I would suggest that rather than trying to jinx a default parameter in a parameterized constructor, you simply define a static struct property which returns your desired default value, and replace every occurrence of new ExampleStruct() with ExampleStruct.NiceDefault;.
2015 Addendum
It appears that C# and VB.NET may ease the prohibition against defining parameterless struct constructors. This may cause a statement like Dim s = New StructType() to assign s a value which is different from the value given to new array items of type StructType. I'm not terribly keen on the change, given that new StructType is often used in places where something analogous to C#'s default(StructType) would be more appropriate if it existed. VB.NET would allow Dim s As StructType = Nothing, but that seems rather hokey.
why do you have public ExampleStruct(int value = 1) : this() ?
shouldn't it be public ExampleStruct(int value = 1)? I think the :this() is creating the no-parameter constructor.

Why we use new keyword for initializing structure though it's a value type

Why do we use the new keyword for initializing a structure even though it's a value type in C#?
Because that is the keyword that the language specification says you use to to initialize a value-type (via either a custom constructor or simply zeroing the memory (the parameterless new() usage on value-types), although there is an edge-case when even this is unnecessary). It would seem odd to add a different language keyword for the same concept. Even more-so if you consider generics:
public static T Create<T>() where T : new() // not terribly helpful, but....
{
return new T();
}
If there were different keywords for reference-types and value-types, this would be very confusing for, say, var zero = Create<int>(). Again, the example is silly, but there is a point in there.
When you create a struct object using the new operator, it gets created and the appropriate constructor is called.
But there is an exception. Structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.
For example:
public struct CoOrds
{
public int x, y;
public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
// Declare an
CoOrds coords1;
// Initialize:
coords1.x = 10;
coords1.y = 20;

C# using the "this" keyword in this situation?

I've completed a OOP course assignment where I design and code a Complex Number class. For extra credit, I can do the following:
Add two complex numbers. The function will take one complex number object as a parameter and return a complex number object. When adding two complex numbers, the real part of the calling object is added to the real part of the complex number object passed as a parameter, and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.
Subtract two complex numbers. The
function will take one complex
number object as a parameter and
return a complex number object. When
subtracting two complex numbers, the
real part of the complex number
object passed as a parameter is
subtracted from the real part of the
calling object, and the imaginary
part of the complex number object
passed as a parameter is subtracted
from the imaginary part of the
calling object.
I have coded this up, and I used the this keyword to denote the current instance of the class, the code for my add method is below, and my subtract method looks similar:
public ComplexNumber Add(ComplexNumber c)
{
double realPartAdder = c.GetRealPart();
double complexPartAdder = c.GetComplexPart();
double realPartCaller = this.GetRealPart();
double complexPartCaller = this.GetComplexPart();
double finalRealPart = realPartCaller + realPartAdder;
double finalComplexPart = complexPartCaller + complexPartAdder;
ComplexNumber summedComplex = new ComplexNumber(finalRealPart, finalComplexPart);
return summedComplex;
}
My question is: Did I do this correctly and with good style? (using the this keyword)?
The use of the this keyword can be discussed, but it usually boils down to personal taste. In this case, while being redundant from a technical point of view, I personally think it adds clarity, so I would use it as well.
Use of the redundant this. is encouraged by the Microsoft coding standards as embodied in the StyleCop tool.
You can also to overload math operators, just like:
public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)
Since you're now learning C# and asking about style, I'm going to show you several things that are wrong with the code you posted along with reasons.
Edit: I only responded to this because it looks like you actually working to figure this stuff out. Since that's the type of people I prefer to work with, I'm more critical simply because I hope it helps you get somewhere better as a result. :)
Structure name
ComplexNumber is unnecessarily long. Note that none of Single, Double, Int32, Int64, etc. have Number in the name. This suggests Complex as a more appropriate name.
Complex matches the naming already established in the .NET Framework.
Real and imaginary components
GetRealPart() and GetComplexPart() should be get-only properties instead of methods.
GetComplexPart() is misnamed because it is actually returning the imaginary part.
Since the .NET framework already has a Complex structure, you shouldn't reinvent the naming. Therefore, unless you are in a position to redefine Framework conventions, the properties must be named Real and Imaginary.
Operations
If you look at existing examples like System.Windows.Vector, you see that math operations are implemented by providing a static method and an operator:
public static Point Add(Vector vector, Point point);
public static Point operator+(Vector vector, Point point);
Not surprisingly, this convention carried over to the System.Numerics.Complex structure:
public static Complex Add(Complex left, Complex right);
public static Complex operator +(Complex left, Complex right);
Summary
The result is clean, easy to verify, and behaves as everyone expects. The this keyword doesn't/can't appear because the methods are static.
public static Complex Add(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
public static Complex operator +(Complex left, Complex right)
{
return new Complex(left.Real + right.Real, left.Imaginary + right.Imaginary);
}
I use this keyword only for variables and when there's an argument that has the same name as the private variable. i.e.
private String firstname;
public SetName(String firstname)
{
this.firstname = firstname;
}
I would say yes, it looks correct and easy to read. But isn't this something your TA should answer?
double realPartCaller = this.GetRealPart();
Even if you omit this from GetRealPart() it should still be okay. But the use of this makes it quite easy to read and understand when it comes to maintainer.
double realPartCaller = this.GetRealPart(); ==> bit more readable IMHO
double realPartCaller = GetRealPart();
I find myself more and more using the this keyword for both methods and properties on the current instance, as I feel it increases readability and maintainability. this is especially useful if your class also has static methods and/or properties, on which you of course can not use the this keyword, as these are not related to the current instance. By using this, you clearly see the difference.
To bring it even further, you should consider using the class name as a qualifier for static methods and properties, even within the class itself.
Just to add completeness to the answers - there is one case when the this keyword is mandatory. That's when you have a local variable (or a method parameter) that has the same name as a class member. In this case writing it without this will access the local variable and with this will set the class member. To illustrate:
class MyClass
{
public int SomeVariable;
public void SomeMethod()
{
int SomeVariable;
SomeVariable = 4; // This assigns the local variable.
this.SomeVariable = 6; // This assigns the class member.
}
}
A couple things that follow from this:
Always avoid giving local variables the same name as class members (I admit, I don't always follow this myself);
Writing this in front of all member accesses acts like a safeguard. If you write a piece of code without it, and then later introduce a local variable with the same name and type as a class member, your code will still compile just fine, but will do something completely different (and probably wrong).
One instance though where I use the same names for method parameters as for class members is in constructors. I often write it like this:
class MyClass
{
public int VariableA;
public string VariableB;
public MyClass(int VariableA, string VariableB)
{
this.VariableA = VariableA;
this.VariableB = VariableB;
}
}
In my opinion this makes the constructor clearer, because you immediately understand which parameter sets which class member.
Usage of this keyword seems fine.
Though I believe for a class like Complex you should store the real and complex part as int properties and use them in the method, rather than using the methods GetRealPart() and GetComplexPart()
I would do it this way:
class ComplexNumber
{
public int RealPart { get; set; }
public int ComplexPart { get; set; }
public ComplexNumber(int real, int complex)
{
this.RealPart = real;
this.ComplexPart = complex;
}
public ComplexNumber Add(ComplexNumber c)
{
return new ComplexNumber(this.RealPart + c.RealPart, this.ComplexPart + c.ComplexPart);
}
}
The following is a scenario where this MUST be used, otherwise, the parameter and not the class member is considered for both LHS and RHS of the assignment.
public ComplexNumber(int RealPart, int ComplexPart)
{
RealPart = RealPart; // class member will not be assigned value of RealPart
ComplexPart = ComplexPart;
}
If you follow the naming conventions, using this is rearlly neded:
class MyClass
{
public int _variableA;
public string _variableB;
public MyClass(int variableA, string variableB)
{
_variableA = variableA;
_variableB = variableB;
}
}

Categories