How to provide int[,] and int values to test method, C# - c#

I need this method for unit testing. There is matrix and method that calculate matrix trace which is integer. So i need to provide simple matrix (int[,]) and expected trace:
[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestReturnTrace(int[,] simpleMatrix, int expected)
{
var mock = new Mock<IMatrixGenerator>();
mock.Setup(a => a.GenerateRandomMatrix()).Returns(simpleMatrix);
MatrixBase matrix = new MatrixBase(mock.Object);
int actual = matrix.ReturnTrace();
Assert.AreEqual(expected, actual);
}
How can i create simple 2D array and integer value and return it?
My best attempt is:
static IEnumerable<object[], int> TestDataMethod()
{
int[,] array2d = new int[,] { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
return (new[] {
new[] { array2d },
myInteger )
};
}
but the error is "No best type found for implicitly-typed array", like if I try to create array, but I just pair two values in parentheses. Where am I wrong?

Your return type doesn't match the method data, you can use tuple (int[,], int) as generic type parameter for IEnumerable<T> and yield return to return a single item.
static IEnumerable<(int[,], int)> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return (array2d, myInteger);
}
Update: just looked at some articles regarding MSTest and DynamicData attribute, like this. The correct approach seems to be using an IEnumerable<object[]>, where every item in object array represents a single argument in test method
static IEnumerable<object[]> TestDataMethod()
{
int[,] array2d = { { 1, 0 }, { 0, 1 } };
int myInteger = 2;
yield return new object[] { array2d, myInteger };
}

Related

how to return two integer values in c#

I tried like below
public int[] GetCompletedCalls()
{
int[] minMax = int[2];
minMax[0] = countCompleted;
minMax[1] = countPendings;
return minMax;
}
But at declaring an array variable throwing an error: Invalid
expression term 'int'
you need to use the new keyword:
int[] minMax = new int[2];
There are multiple ways to achieve this. The easiest one needs only a single correction:
int[] minMax = int[2];
should be
int[] minMax = new int[2];
Another opportunity is to do this:
return new [] { countCompleted, countPendings};
or also this:
public void GetCompletedCalls(out int completed, out int pending)
{
completed = countCompleted;
pending = countPendings;
}
or also this which uses a Tuple instead (requires C#7):
public (int, int) GetCompletedCalls()
{
return (countCompleted, countPendings);
}

How to get a complete row or column from 2D array in C#

I do not want to use a jagged array and I have a 2D array and I want to get a complete column or row without looping through it. Does anyone have an idea how it can be done.
double [,] array = new double [3,3] ;
1 2 3
4 5 6
Out: 1 2 3 or 2 5
To get a specific row or column from the multidimensional array you can use some LINQ:
public class CustomArray<T>
{
public T[] GetColumn(T[,] matrix, int columnNumber)
{
return Enumerable.Range(0, matrix.GetLength(0))
.Select(x => matrix[x, columnNumber])
.ToArray();
}
public T[] GetRow(T[,] matrix, int rowNumber)
{
return Enumerable.Range(0, matrix.GetLength(1))
.Select(x => matrix[rowNumber, x])
.ToArray();
}
}
You can optimise it for getting rows by using Buffer.BlockCopy(), but to get a column you'll have to loop. Buffer.BlockCopy() ultimately uses a processor instruction to copy a block of memory, so it is pretty fast.
It's convenient to put the code into an extension method to make it easier to call. Note that Buffer.BlockCopy() can only be used on arrays of primitive types, i.e. int, double, char etc. This does NOT include string.
Here's a compilable example:
using System;
using System.Linq;
using System.Runtime.InteropServices;
namespace ConsoleApplication4
{
public static class Program
{
private static void Main()
{
var array = new [,]
{
{0.1, 0.2, 0.3, 0.4, 0.5},
{1.1, 1.2, 1.3, 1.4, 1.5},
{2.1, 2.2, 2.3, 2.4, 2.5},
{3.1, 3.2, 3.3, 3.4, 3.5},
};
var row = array.GetRow(2);
// This prints 2.1, 2.2, 2.3, 2.4, 2.5
Console.WriteLine(string.Join(", ", row.Select(element => element.ToString())));
}
}
public static class ArrayExt
{
public static T[] GetRow<T>(this T[,] array, int row)
{
if (!typeof(T).IsPrimitive)
throw new InvalidOperationException("Not supported for managed types.");
if (array == null)
throw new ArgumentNullException("array");
int cols = array.GetUpperBound(1) + 1;
T[] result = new T[cols];
int size;
if (typeof(T) == typeof(bool))
size = 1;
else if (typeof(T) == typeof(char))
size = 2;
else
size = Marshal.SizeOf<T>();
Buffer.BlockCopy(array, row*cols*size, result, 0, cols*size);
return result;
}
}
}
As of March 2021, you can now use the very cool Span2D class for this!
If you are happy using spans (I highly recommend reading about them, they are awesome), you can use the following code
var span2D = new Span2D<double>(array);
//Gets the first row and returns a span of it
var rowSpan = span2D.GetRowSpan(0);
foreach(var number in rowSpan)
{
//Do something with numbers
}
//Gets the 2nd Column as a RefEnumerable and converts it to an array
var column = span2D.GetColumn(1).ToArray();
Here is how i have done it you can use
GetLength(0)
to get the columns and use
GetLength(1)
to get the rows of the 2 Dimensional array and you loop thru it with the for loop if any one else needs this.
string text = "";
for (int i = 0; i < array.GetLength(0); i++)
{
text += Convert.ToString(array[i, 2]) + "\n";
}
an alternative way you can do it is by using a List instead of an array.
Specifically in your case you'd do something like that:
Initially create an inner class that represents a tuple of the array
Create a List of the inner class
Populate the inner class
Get the row that contains something specific
Get the column that contains something specific
public static void Main(string[] args)
{
// #2 -- Instantiate List of myClass
List<myClass> myList = new List<myClass>();
//
// #3 -- Populate the list
myList.Add(new myClass(1,2,3));
myList.Add(new myClass(3,4,5));
myList.Add(new myClass(5,6,6));
//
// #4 -- Get the line where a == 1
myList.Find(x=>x.a == 1);
//
// #5 -- Get column b
myList.Select(x=>x.b);
}
// #1 -- Create the inner class
public class myClass
{
public int a;
public int b;
public int c;
public myClass(int a, int b, int c)
{
this.a =a;
this.b =b;
this.c =c;
}
}
what is needed is a jagged array (not a multidimensional array)
https://msdn.microsoft.com/en-us/library/2s05feca.aspx
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
full example with columns:
using System;
using System.Collections.Generic;
namespace Rextester
{
public class Program
{
public static T[] column<T>(T[][] jaggedArray,int wanted_column)
{
T[] columnArray = new T[jaggedArray.Length];
T[] rowArray;
for(int i=0;i<jaggedArray.Length;i++)
{
rowArray=jaggedArray[i];
if(wanted_column<rowArray.Length)
columnArray[i]=rowArray[wanted_column];
}
return columnArray;
}
public static void Main(string[] args)
{
//Your code goes here
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
Console.WriteLine("Hello, world!");
Console.WriteLine(string.Join(" ",jaggedArray[1]));
Console.WriteLine(string.Join(" ",column(jaggedArray,1)));
}
}
}
similar idea, using extensions:
using System;
using System.Collections.Generic;
namespace Rextester
{
public static class MyExtensions
{
public static string Extend(this Array array)
{
return "Yes, you can extend an array";
}
public static T[] column<T>(this T[,] multidimArray,int wanted_column)
{
int l=multidimArray.GetLength(0);
T[] columnArray = new T[l];
for(int i=0;i<l;i++)
{
columnArray[i]=multidimArray[i,wanted_column];
}
return columnArray;
}
public static T[] row<T>(this T[,] multidimArray,int wanted_row)
{
int l=multidimArray.GetLength(1);
T[] rowArray = new T[l];
for(int i=0;i<l;i++)
{
rowArray[i]=multidimArray[wanted_row,i];
}
return rowArray;
}
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
int [,] multidimArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Console.WriteLine(string.Join(" ",multidimArray.column(0)));
Console.WriteLine(string.Join(" ",multidimArray.row(0)));
}
}
}
My use case differs from the question, but is similar. I needed a 2D array of float[2] arrays, that I was using to represent complex numbers.
float[,,] myarray = new float[100,100,2];
float[] result = myarray[1,1]; <-- fails to compile needs all 3 coordinates
The jagged array Simmon mentioned provided the solution.
float[,][] myarray = new float[100,100][];
...
myarray[x,y] = new float[2]; <-- Initialise all elements of jagged 2D array in loop
...
float[] result = [100,100];
if you know the index of the numbers to output..then you don't need to use a loop to get the output desired...
double[,] array = new double[3,3] {{1,2,3}, {4,5,6}, {7,8,9}};
int firstNum = array[0,1];
int secondNum = array[1,1];
this will get 2, 5

Array comprasion as Dictionary keys in C#

I want to create class representing n-dimensional array, but where is a commutative access to its elements. e.g: a[new[] {4, 7, 55}] == a[new[] {55, 4, 7}]
I write this code, where I implement interface IEqualityComparer in order to compare keys (which are arrays) by their real content, but not refs.
using System;
using System.Collections.Generic;
using System.Linq;
class NArray
{
public int this[int[] x]
{
get
{
Array.Sort(x);
return array[x];
}
set
{
Array.Sort(x);
array[x] = value;
}
}
public void Remove(int[] x)
{
Array.Sort(x);
array.Remove(x);
}
Dictionary<int[], int> array = new Dictionary<int[], int>(new ArrCmpr());
}
class ArrCmpr : IEqualityComparer<int[]>
{
public bool Equals(int[] a, int[] b)
{
return a.Length == b.Length && Enumerable.Range(0, a.Length).All(i => a[i] == b[i]);
}
public int GetHashCode(int[] a)
{
return a.GetHashCode();
}
}
But when I start to use this class I encounter an exception: "System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary." This exception occurs in next both cases when I try to output the element to console:
NArray a = new NArray();
a[new[] { 1, 3, 2 }] = 4;
Console.WriteLine(a[new[] { 3, 2, 1 }]); //error
 
NArray b = new NArray();
b[new[] { 1, 2, 3 }] = 4;
Console.WriteLine(b[new[] { 1, 2, 3 }]); //error
So what is the cause of that problem and how could I fix it?
That's because your implementation of GetHashCode is incorrect: two different arrays with the same items in the same order usually won't have the same hashcode (because the values are not taken into account), so Equals is never called.
You need an implementation of GetHashCode that takes the values in the array into account:
class ArrCmpr : IEqualityComparer<int[]>
{
public bool Equals(int[] a, int[] b)
{
return a.SequenceEqual(b);
}
public int GetHashCode(int[] a)
{
return a.Aggregate(0, (acc, i) => unchecked(acc * 457 + i * 389));
}
}
To me seems that GetHashCode have to be changed as it simply returns the hash code of Array object, considering the fact that you use NEW hashcode every time will be different, even if content equal.
Since you're using a Dictionary to store your arrays you need to check if the key exists already, and only then can you access it with the [] operator, otherwise if you try to access a key that doesn't exist an exception is thrown
// your get function
if(array.ContainsKey(x))
return array[x];
else // do something like return null
return null;
// your set function
if(array.ContainsKey(x))
array[x] = value;
else
array.Add(x, value);

All possible array initialization syntaxes

What are all the array initialization syntaxes that are possible with C#?
These are the current declaration and initialization methods for a simple array.
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2
Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.
Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as
var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
The array creation syntaxes in C# that are expressions are:
new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }
In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.
In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.
In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.
In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.
There is also a syntax which may only be used in a declaration:
int[] x = { 10, 20, 30 };
The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.
there isn't an all-in-one guide
I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".
Non-empty arrays
var data0 = new int[3]
var data1 = new int[3] { 1, 2, 3 }
var data2 = new int[] { 1, 2, 3 }
var data3 = new[] { 1, 2, 3 }
var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.
Empty arrays
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { } and int[] data9 = new [] { } are not compilable.
var data10 = { } is not compilable. Use int[] data11 = { } instead.
As an argument of a method
Only expressions that can be assigned with the var keyword can be passed as arguments.
Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 }) is not compilable
Foo(new int[0])
Foo(new int[] { })
Foo({}) is not compilable
Enumerable.Repeat(String.Empty, count).ToArray()
Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.
In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:
var array = Enumerable.Repeat(string.Empty, 37).ToArray();
Also please take part in this discussion.
var contacts = new[]
{
new
{
Name = " Eugene Zabokritski",
PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
},
new
{
Name = " Hanying Feng",
PhoneNumbers = new[] { "650-555-0199" }
}
};
Example to create an array of a custom class
Below is the class definition.
public class DummyUser
{
public string email { get; set; }
public string language { get; set; }
}
This is how you can initialize the array:
private DummyUser[] arrDummyUser = new DummyUser[]
{
new DummyUser{
email = "abc.xyz#email.com",
language = "English"
},
new DummyUser{
email = "def#email.com",
language = "Spanish"
}
};
Just a note
The following arrays:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };
Will be compiled to:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
Repeat without LINQ:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
int[] array = new int[4];
array[0] = 10;
array[1] = 20;
array[2] = 30;
or
string[] week = new string[] {"Sunday","Monday","Tuesday"};
or
string[] array = { "Sunday" , "Monday" };
and in multi dimensional array
Dim i, j As Integer
Dim strArr(1, 2) As String
strArr(0, 0) = "First (0,0)"
strArr(0, 1) = "Second (0,1)"
strArr(1, 0) = "Third (1,0)"
strArr(1, 1) = "Fourth (1,1)"
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
Another way of creating and initializing an array of objects. This is similar to the example which #Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.
IUser[] userArray = new IUser[]
{
new DummyUser("abc#cde.edu", "Gibberish"),
new SmartyUser("pga#lna.it", "Italian", "Engineer")
};
Classes for context:
interface IUser
{
string EMail { get; } // immutable, so get only an no set
string Language { get; }
}
public class DummyUser : IUser
{
public DummyUser(string email, string language)
{
m_email = email;
m_language = language;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
}
public class SmartyUser : IUser
{
public SmartyUser(string email, string language, string occupation)
{
m_email = email;
m_language = language;
m_occupation = occupation;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
private string m_occupation;
}
For the class below:
public class Page
{
private string data;
public Page()
{
}
public Page(string data)
{
this.Data = data;
}
public string Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
you can initialize the array of above object as below.
Pages = new Page[] { new Page("a string") };
Hope this helps.
hi just to add another way:
from this page :
https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1
you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:
using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();
You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.
Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());
int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
Console.WriteLine(i);
}
Console.ReadKey();
Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.
NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
To initialize an empty array, it should be Array.Empty<T>() in dotnet 5.0
For string
var items = Array.Empty<string>();
For number
var items = Array.Empty<int>();
Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.
Now I've not tested all of this so I'll put what I've tested (static member and static function)
Class x {
private static Option[] options = GetOptionList();
private static Option[] GetOptionList() {
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.
I imagine something like the following (but it doesn't work)
Class x {
private static Option[] options = () => {
Lots of prep stuff here that means we can not just use the next line
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
Basically a way of just declaring the function for the scope of filling the variable.
I'd love it if someone can show me how to do that.
For multi-dimensional array in C# declaration & assign values.
public class Program
{
static void Main()
{
char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };
int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
}
}

How to put several ints into an int array c# [duplicate]

What are all the array initialization syntaxes that are possible with C#?
These are the current declaration and initialization methods for a simple array.
string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2
Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.
Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as
var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2
The array creation syntaxes in C# that are expressions are:
new int[3]
new int[3] { 10, 20, 30 }
new int[] { 10, 20, 30 }
new[] { 10, 20, 30 }
In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.
In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.
In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.
In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.
There is also a syntax which may only be used in a declaration:
int[] x = { 10, 20, 30 };
The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.
there isn't an all-in-one guide
I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".
Non-empty arrays
var data0 = new int[3]
var data1 = new int[3] { 1, 2, 3 }
var data2 = new int[] { 1, 2, 3 }
var data3 = new[] { 1, 2, 3 }
var data4 = { 1, 2, 3 } is not compilable. Use int[] data5 = { 1, 2, 3 } instead.
Empty arrays
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { } and int[] data9 = new [] { } are not compilable.
var data10 = { } is not compilable. Use int[] data11 = { } instead.
As an argument of a method
Only expressions that can be assigned with the var keyword can be passed as arguments.
Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 }) is not compilable
Foo(new int[0])
Foo(new int[] { })
Foo({}) is not compilable
Enumerable.Repeat(String.Empty, count).ToArray()
Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.
In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:
var array = Enumerable.Repeat(string.Empty, 37).ToArray();
Also please take part in this discussion.
var contacts = new[]
{
new
{
Name = " Eugene Zabokritski",
PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
},
new
{
Name = " Hanying Feng",
PhoneNumbers = new[] { "650-555-0199" }
}
};
Example to create an array of a custom class
Below is the class definition.
public class DummyUser
{
public string email { get; set; }
public string language { get; set; }
}
This is how you can initialize the array:
private DummyUser[] arrDummyUser = new DummyUser[]
{
new DummyUser{
email = "abc.xyz#email.com",
language = "English"
},
new DummyUser{
email = "def#email.com",
language = "Spanish"
}
};
Just a note
The following arrays:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };
Will be compiled to:
string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };
Repeat without LINQ:
float[] floats = System.Array.ConvertAll(new float[16], v => 1.0f);
int[] array = new int[4];
array[0] = 10;
array[1] = 20;
array[2] = 30;
or
string[] week = new string[] {"Sunday","Monday","Tuesday"};
or
string[] array = { "Sunday" , "Monday" };
and in multi dimensional array
Dim i, j As Integer
Dim strArr(1, 2) As String
strArr(0, 0) = "First (0,0)"
strArr(0, 1) = "Second (0,1)"
strArr(1, 0) = "Third (1,0)"
strArr(1, 1) = "Fourth (1,1)"
For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };
Another way of creating and initializing an array of objects. This is similar to the example which #Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.
IUser[] userArray = new IUser[]
{
new DummyUser("abc#cde.edu", "Gibberish"),
new SmartyUser("pga#lna.it", "Italian", "Engineer")
};
Classes for context:
interface IUser
{
string EMail { get; } // immutable, so get only an no set
string Language { get; }
}
public class DummyUser : IUser
{
public DummyUser(string email, string language)
{
m_email = email;
m_language = language;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
}
public class SmartyUser : IUser
{
public SmartyUser(string email, string language, string occupation)
{
m_email = email;
m_language = language;
m_occupation = occupation;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
private string m_occupation;
}
For the class below:
public class Page
{
private string data;
public Page()
{
}
public Page(string data)
{
this.Data = data;
}
public string Data
{
get
{
return this.data;
}
set
{
this.data = value;
}
}
}
you can initialize the array of above object as below.
Pages = new Page[] { new Page("a string") };
Hope this helps.
hi just to add another way:
from this page :
https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1
you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:
using System.Linq
.....
public int[] arrayName = Enumerable.Range(0, 9).ToArray();
You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.
Console.Write("Enter size of array");
int n = Convert.ToInt16(Console.ReadLine());
int[] dynamicSizedArray= new int[n]; // Here we have created an array of size n
Console.WriteLine("Input Elements");
for(int i=0;i<n;i++)
{
dynamicSizedArray[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Elements of array are :");
foreach (int i in dynamicSizedArray)
{
Console.WriteLine(i);
}
Console.ReadKey();
Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.
NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback
To initialize an empty array, it should be Array.Empty<T>() in dotnet 5.0
For string
var items = Array.Empty<string>();
For number
var items = Array.Empty<int>();
Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.
Now I've not tested all of this so I'll put what I've tested (static member and static function)
Class x {
private static Option[] options = GetOptionList();
private static Option[] GetOptionList() {
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.
I imagine something like the following (but it doesn't work)
Class x {
private static Option[] options = () => {
Lots of prep stuff here that means we can not just use the next line
return (someSourceOfData).Select(dataitem => new Option()
{field=dataitem.value,field2=dataitem.othervalue});
}
}
Basically a way of just declaring the function for the scope of filling the variable.
I'd love it if someone can show me how to do that.
For multi-dimensional array in C# declaration & assign values.
public class Program
{
static void Main()
{
char[][] charArr = new char[][] { new char[] { 'a', 'b' }, new char[] { 'c', 'd' } };
int[][] intArr = new int[][] { new int[] { 1, 2 }, new int[] { 3, 4 } };
}
}

Categories