Passing array by value in c# - c#

As far as I understand, the default type or argument passing in c# is by value. Therefore no statement is required. But when I try the run following code, my A matrix in Main is being modified by the operations done to dMatrixU in the Factorize() method of class Decomposition. I'm sure the problem is in the constructor of the Decomposition when I just assing A to dMatrixU, the reference of A is being assigned instead of the values. Therefore my question on how to avoid this, all I have found is how to pass the arguments by reference. Again, as I understand no modifier is needed for passing the argument by value. Where am I wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using LinearEquations;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
double[,] A = new double[,]
{ { 1, 1, 1 } ,
{ 4, 3, -1 } ,
{ 3, 5, 3 } };
double[] B = new double[] {1,6,4};
Decomposition lu = new Decomposition(A,B);
lu.Factorize();
PrintMatrix(A,"A:");
PrintVector(B,"B:");
PrintMatrix(lu.L,"L:");
PrintMatrix(lu.U,"U:");
PrintVector(lu.D,"D:");
}
public static void PrintMatrix(double[,] M, String Title = "Matrix: ")
{
Console.WriteLine(Title);
for(int i = 0; i<M.GetLength(0); i++)
{
for(int j = 0; j<M.GetLength(1);j++)
{
Console.Write(M[i,j]+"\t");
}
Console.Write("\n");
}
Console.Write("\n");
}
public static void PrintVector(double[] V, String Title = "Vector: ",bool AsRow = true)
{
String str = (AsRow)? "\t" : "\n";
Console.WriteLine(Title);
for(int i = 0; i<V.GetLength(0); i++)
{
Console.Write(V[i]+str);
}
Console.WriteLine("\n");
}
}
}
namespace LinearEquations
{
public class Decomposition
{
// Fields
private double[,] dMatrixA; // Parameter in A*X=B
private double[] dVectorB; // Parameter in A*X=B
private double[] dVectorX; // Result wanted in A*X=B
private double[,] dMatrixU; // A splits into L and U
private double[,] dMatrixL; // L is used to calculate D in L*D=B
private double [] dVectorD; // D is used to calculate X in U*X=D
// Properties
public double[,] A
{
get { return dMatrixA; }
set { dMatrixA = value; }
}
public double[] B
{
get { return dVectorB; }
set { dVectorB = value; }
}
public double[] X
{
get { return dVectorX; }
set { dVectorX = value; }
}
public double[,] L
{
get { return dMatrixL; }
set { dMatrixL = value; }
}
public double[,] U
{
get { return dMatrixU; }
set { dMatrixU = value; }
}
public double[] D
{
get { return dVectorD; }
set { dVectorD = value; }
}
// Constructor
public Decomposition(double[,] A, double[] B)
{
dMatrixA = A;
dVectorB = B;
dVectorX = new double[B.Length];
dMatrixU = A;
dMatrixL = new double[A.GetLength(0),A.GetLength(1)];
dVectorD = new double[B.Length];
}
// Split A into L and U
public void Factorize()
{
// Iterate per each row
for(int i = 0; i<dMatrixU.GetLength(0); i++)
{
// For all the rows make element i equals 0
for(int j = i+1; j<dMatrixU.GetLength(0);j++)
{
// Factor that assures substraction makes 0
dMatrixL[1,1] = dMatrixU[j,i] / dMatrixU[i,i];
// Iterate per each column
for(int k = 0; k<dMatrixU.GetLength(1);k++)
{
dMatrixU[j,k] = dMatrixU[j,k] - dMatrixU[i,k]*dMatrixL[1,1];
}
}
}
}
}
}

As far is i understand, the default type or argument passing in c# is by value.
Unfortunately it is a bit more complicated and also has some execptions:
Reference types like Decomposition you hand in by making a copy of the reference. Unfortunately that means both still reference the same instance in memory. So despite a copy operation, it is call-by-Reference.
With value types like Int or double and their aliases, usually a copy is made. I do not know of any case where it does not, but I was wrong on those things before. So they are call by value.
Finally String and a few other reference types are inmutable by design. That has the advantage that they behave kinda like value types in this area. You hand in a Reference, but the instance itself can not be changed. The code can only create a new instance in memory with a different value. So despite handing over literal references, it kinda works like call by value.
Your specific case
Arrays are very explicitly Reference types. Handing them into a function without side effects, requires proper cloning. If it is a array of reference types, the cloning must be deep.
In your case you have arrays of value types. If you want to avoid call-by-reference side effects, you those arrays must be cloned. However as double is a value type, this cloning can be shallow. No need for a deep clone.
Unlike Java there is not a dedicated Clone() Method. And I am not sure why exactly. However you can often use one Collection to initialize another through the constructor. Or they even have a function like Array.Copy(), as TheBatman pointed out.

Related

Reference several class members

I want to access three members of a class (_orderDay, _orderCustody, _orderBox) according to and indexing variable (orderIndex), using a different approach than in the following example
public class COrdering
{
private int _orderDay;
private int _orderCustody;
private int _orderBox;
public COrdering() { _orderDay = _orderCustody = _orderBox = 0; }
public int IncOrder(int orderIndex)
{
int v = orderIndex == 0 ? _orderDay : (orderIndex == 1 ? _orderCustody : _orderBox);
v++;
if (orderIndex == 0) _orderDay = v
else if (orderIndex == 1) _orderCustody = v;
else _orderBox = v;
return v;
}
}
The idea is to use less coding than in the previous example. When I coded something like this in C++ I used std::bind to create a const array of references to each field involved, but I don't know how to make something similar in C#. Can anyone help me out with this?
EDIT
I've found a way to optimize IncOrder method:
//...
private int _incDay() { return ++_orderDay; }
private int _incCustody() { return ++_orderCustody; }
private int _incBox() { return ++_orderBox; }
private IReadOnlyList<Func<int>> _funcs = Array.AsReadOnly(new Func<int>[] {_incDay, _incCustody, incBox});
public int IncOrder(int orderIndex) { return _funcs[orderIndex](); }
There may be another way, such as creating an array of references to these fields, but I don't know if that's possible.
Sounds like a job for an index operator overload:
public int this[int index] => IncOrder(index);
Usage:
COrdering ordering = new COrdering();
int newValue = ordering[0];
Updated - you can use an array internally
public class COrdering
{
public enum OrderIndex { Day = 0, Custody = 1, Box = 2, NumElements };
private readonly int[] values = new int[(int)OrderIndex.NumElements];
public int IncOrder(OrderIndex orderIndex) => ++values[(int)orderIndex];
public int this[OrderIndex index] => IncOrder(index);
}
Also, your constructor can be removed, in C# everything is auto initialized to 0 (or null for reference types).
Why not use a Dictionary<int, int>?
public class COrdering
{
Dictionary<int, int> map = new Dictionary<int, int>();
public COrdering() { map[0] = 0; map[1] = 0; map[2] = 0; }
public int IncOrder(int orderIndex)
{
return ++map[orderIndex];
}
}
In fact you can even use an int[] or a List<int>.
I understand you want to simplify your code, so in that case start by the variables where you save data, if you are accessing them by index it would make more sense to declare an array and use an enum, something like this:
public class COrdering
{
enum OrderType
{
Day = 0,
Custody = 1,
Box = 2,
Count = 3
};
private int[] _order = new int[(int)OrderType.Count];
public int IncOrder(OrderType orderIndex)
{
// Increment corresponding order type and return its value
return ++_order[(int)orderIndex];
}
}
You can see that you implement your IncOrder with just one line of code. The ++ must be before the variable name, so you get the correct answer. I either use an intermediate variable for the increment or a ++ preceded of a good comment, so that the next programmer will see it.
The other solution with [] overload is unexpected and surprising for the next guy debugging your code :-) so that being said I suppose you guess which one I'd chose.

In C# is there a way to use properties with arrays?

The way I understand it, C# properties are methods that have the get and set accessors.
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
I can call the property of the class in a script (and its accessors) with
MyClass mc = new MyClass();
mc.X = 10;
Debug.Log(mc.X); //returns 10
To my knowledge, however, I can pass only one value to the property.
Is there a way to pass arrays? Something like
MyClass mc = new MyClass();
mc.X = new int[] { 1, 2 }; //throws an error
Debug.Log(mc.X[0]); //I'd like it to return 1
This throws an error of course. I wonder if it's possible to do it any other way.
The solution is simple - use int[] instead of int
class MyClass
{
private int[] x;
public int[] X
{
get
{
return x;
}
set
{
x = value;
}
}
}
Also you might consider using auto property instead just like this:
class MyClass
{
public int[] X { get; set; }
}
You might also want to take a look at the Lists and read some basics ;)
Sure, just make the property an array or list also:
class MyClass
{
// in general a list should never be null, but could be empty, or without values.
// thats why we initialize the field here
private List<int> x = new List<int>();
public List<int> X
{
get
{
return x;
}
set
{
x = value;
}
}
}
then you could do:
var obj = new MyClass();
obj.X.Add(3);
obj.X.Add(6);
// (or use AddRange() to add another list or array of values
// Then loop the list and output values:
foreach(int x in obj.X)
{
Console.WriteLine(x);
}
Here's a dotnetfiddle for the above code:
https://dotnetfiddle.net/T2FrQ0

Concatenating two arrays results in two modified arrays instead of one C#

I have a very strange Behavior when merging two arrays together:
Assumptions
I have a class Tensor which contains an array float[] and a function AddTensorElements:
class Tensor
{
public float[] MovingAverage3h { get; set; }
public float[] MovingAverage6h { get; set; }
public float[] MovingAverage1d { get; set; }
public void AddTensorElements(Tensor input)
{
if (this.MovingAverage3h == null)
this.MovingAverage3h = input.MovingAverage3h;
this.MovingAverage6h = input.MovingAverage6h;
this.MovingAverage1d = input.MovingAverage1d;
}
else
{
this.MovingAverage3h = Concat(this.MovingAverage3h, input.MovingAverage6h);
this.MovingAverage6h = Concat(this.MovingAverage6h, input.MovingAverage6h);
this.MovingAverage1d = Concat(this.MovingAverage1d, input.MovingAverage1d);
}
private float[] Concat (float[] first, float[] second)
{
List<float> concatenated = new List<float>();
concatenated.AddRange(first);
concatenated.AddRange(second);
//foreach (float value in first) concatenated.Add(value);
//foreach (float value in second) concatenated.Add(value);
float[] returnArray = concatenated.ToArray();
return returnArray;
}
}
Within my main program, I repeatedly add the tensor M6t to the base tensor Minutes30[i]
class TensorCreator
{
private static List<Elements.Tensor> Minutes30 = new List<Elements.Tensor>();
private static void AddValues(Tensor M6t)
{
// Fill Minutes 30
Minutes30.Add(M6t);
for (int i = CounterM30; i < Minutes30.Count-1; i += M6)
{
{ } // Issue come up right here
Minutes30[i].AddTensorElements(M6t);
{ } // Issue come up right here
}
}
public static void AppendDataToTensor(Elements.Tensor queueElement)
{
// ...
AddValues(M6Avg);
}
}
Expected behavior vs actual behavior
The array within Minutes[i] expands
The array within M6t staysfloat[1]
So far so good, this works in a tiny separate test application
Within my actual application, the same code lets the baseTensor expand but also the input tensor gets expanded!
for (int i = CounterM30; i < Minutes30.Count-1; i += M6)
{
// M6T.Length == 1;
Minutes30[i].AddTensorElements(M6t);
// M6T.Length == Minutes30[i].Length;
}
strangely, whitin AddtensorToElements() I can see the values changing as well:
The Issue lies right here:
Minutes30.Add(M6t);
This adds a reference of Class Tensor M6t to Minutes 30. The result is that Minutes30[i] gets concatenated with it self.
Solution:
In class Tensor, add a Clone() method
public Tensor Clone()
{
Tensor tensor = new Tensor();
tensor.MovingAverage3h = this.MovingAverage3h.ToArray();
tensor.MovingAverage6h = this.MovingAverage6h.ToArray();
tensor.MovingAverage1d = this.MovingAverage1d.ToArray();
return tensor;
}
then change
Minutes30.Add(M6t);
to
Minutes30.Add(M6t.Clone());

Returning a reference of a struct instead of a copy on C# 3.0?

I have this code:
using System;
using System.Collections.Generic;
using UnityEngine;
public interface HaveId
{
int id { get; }
}
public struct BusinessData : HaveId
{
// business type data
public int graphic_asset_id;
public string name;
public int id { get; set; }
}
public class LookupHelper<T> where T: HaveId
{
private T[] _list;
public T[] list
{
get { return _list; }
set { _list = value; _mapToDictionary(); }
}
private Dictionary<int, int> idxById = new Dictionary<int, int>();
public LookupHelper(){}
private void _mapToDictionary()
{
if(idxById.Count > 0) idxById = new Dictionary<int, int>();
for(var z =0 ; z < list.Length; ++z)
{
idxById[list[z].id] = z;
}
}
public bool IsIdExists(int id)
{
return idxById.ContainsKey(id);
}
public T ById(int id) // is this a reference?
{
var idx = idxById[id];
if (idx >= list.Length) throw new Exception(
String.Format("Invalid Index: {0} >= {1} on {2}",idx.ToString(),list.Length.ToString(), typeof(T).Name)
);
return list[idx];
}
}
And the test code:
LookupHelper<BusinessData> bd = new LookupHelper<BusinessData>();
bd.list = new BusinessData[]
{
new BusinessData{id = 1, name = "test"},
new BusinessData{id = 2, name = "test2"},
};
bd.ById(1).name = "foo";
This give an error: "Cannot modify struct member when accessed struct is not classified as a variable"
How can I change the value of first BusinessData and keep the array still allocated on a contiguous memory (array of struct, needed for cache locality)?
This should be a simple matter of splitting it up into a few lines. Extract the object to get a copy, modify the copy, then overwrite it in the array:
BusinessData bsd = bd.ById(1);
bsd.name = "foo";
bd.SetById(1, bsd);
Of course, you'll need to write that SetById method to reinsert things into the array:
public void SetById(int id, T obj)
{
Int32 idx = idxById[id];
list[idx] = obj;
}
As you know C# borrowed something’s from C and Java. But not everything.
In C, you can create a place for struct on the stack or the heap. On the heap, I can then pass a pointer around and change the content. Very powerful.
But C# emphasizes ease of memory management via garbage collection. To make it easy, C# has the concept of boxing value types into System.Object. Additional details, can be found on Microsoft C# Programming Guide on Boxing and unboxing.
So when you access the value type in your list, you have to explicitly unbox the value. Therefore it’s a copy of the item in the list. You can do what #Nyerguds suggested.
But to make life easy, why not turn your BusinessData into a class?

diplaying data in private array by using indexers in c#

I am declaring two private arrays in indexes and displaying the data in main. However, it is not displaying any one tell me how to display the data in the two private arrays in indexers?
class Program
{
static void Main(string[] args)
{
student sc = new student();
for (int i = 0; i < sc.mlength; i++)
{
Console.WriteLine(sc[i]);
}
Console.ReadLine();
//i am declaring two private arrays in indexes and displaying the data in main is not displaying any one tell me how to display the data in the two private arrays in indexers?
}
}
public class student
{
private int[] _marks = new int[] { 60, 68, 70 };
private string[] _names = new string[] { "suri", "kumar", "suresh" };
public int this[int i]
{
get
{
return _marks[i];
}
set
{
_marks[i] = value;
}
}
public string this[int i]
{
get
{
return _names[Convert.ToInt32(i)];
}
set
{
_names[Convert.ToInt32(i)] = value;
}
}
public int mlength
{
get
{
return _marks.Length;
}
}
public int nlenght
{
get
{
return _names.Length;
}
}
}
}
Indexers allow your class to be used just like an array. On the inside of a class, you manage a collection of values any way you want. These objects could be a finite set of class members, another array, or some complex data structure. Regardless of the internal implementation of the class, its data can be obtained consistently through the use of indexers. Here’s an example.
Example:
using System;
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = new string[size];
for (int i=0; i < size; i++)
{
myData[i] = "empty";
}
}
public string this[int pos]
{
get
{
return myData[pos];
}
set
{
myData[pos] = value;
}
}
static void Main(string[] args)
{
int size = 10;
IntIndexer myInd = new IntIndexer(size);
myInd[9] = "Some Value";
myInd[3] = "Another Value";
myInd[5] = "Any Value";
Console.WriteLine("\nIndexer Output\n");
for (int i=0; i < size; i++)
{
Console.WriteLine("myInd[{0}]: {1}", i, myInd[i]);
}
}
}
The IntIndexer class has a string array named myData. This is a private array that external users can’t see. This array is initialized in the constructor, which accepts an int size parameter, instantiates the myData array, and then fills each element with the word “empty”.
The IntIndexer class has a string array named myData. This is a private array that external users can’t see. This array is initialized in the constructor, which accepts an int size parameter, instantiates the myData array, and then fills each element with the word “empty”.
The next class member is the Indexer, which is identified by the this keyword and square brackets, this[int pos]. It accepts a single position parameter, pos. As you may have already guessed, the implementation of an Indexer is the same as a Property. It has get and setaccessors that are used exactly like those in a Property. This indexer returns a string, as indicated by the string return value in the Indexer declaration.
The Main() method simply instantiates a new IntIndexer object, adds some values, and prints the results. Here’s the output:
Indexer Output
myInd[0]: empty
myInd[1]: empty
myInd[2]: empty
myInd[3]: Another Value
myInd[4]: empty
myInd[5]: Any Value
myInd[6]: empty
myInd[7]: empty
myInd[8]: empty
myInd[9]: Some Value

Categories

Resources