Creating objects from constructors with arrays [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm a newbie and I'm trying to Console.Write() arrays from a constructor in Main. I am also trying to override ToString() to Console.Write() an array of ints as a string, but haven't found a clue how to do it.
namespace Z1
{
class List
{
public List(int b)
{
int[] tabb = new int[b];
Random r1 = new Random();
for(int i=0;i<b;i++)
{
tabb [i] =r1.Next(0, 100);
}
}
public List()
{
Random r2 = new Random();
int rInt1=r2.Next(0,10);
int[] tabc = new int[rInt1];
Random r3 = new Random();
for(int i=0;i<rInt1;i++){
tabc [i] = r3.Next(0,100);
}
}
}
class Program
{
static void Main()
{
List l1 = new List(10);
List l2 = new List();
Console.WriteLine(l1.ToString());
Console.WriteLine(l2.ToString());
}
}
}

The first thing to change are the two arrays. They are local variables and when you exit from the constructor they are simply discarded and you cannot use them anymore. I think you want just one array that could be created with a size specified by your user or with a random size between 1 and 10.
Finally you can override of ToString() in the usual way and return a Join of the array
class List
{
static Random r1 = new Random();
private int[] tabb;
public List(int b)
{
tabb = new int[b];
for (int i = 0; i < b; i++)
tabb[i] = r1.Next(0, 100);
}
// This constructor calls the first one with a random number between 1 and 10
public List(): this(r1.Next(1,11))
{ }
public override string ToString()
{
return string.Join(",", tabb);
}
}
Now your Main method could get the expected result.
As a side note, I suppose that this is just a test program so there is not much concern, but in a real program I strongly suggest you to avoid creating class with names that clashes with the classes defined in the framework. It is better to avoid names likes List, Task, Queue etc...

You can't just print the array, you'll have to print each value separately. Try using this instead of just Console.WriteLine();. Also make sure at the top of your class you have using LINQ;
l1.ToList().ForEach(Console.WriteLine);
l2.ToList().ForEach(Console.WriteLine);

Related

Deep copy a class with arrays [duplicate]

This question already has answers here:
C# Copy Array by Value
(8 answers)
Copy one 2D array to another 2D array
(4 answers)
Closed 2 years ago.
This is an addendum to a previous question I asked about copying classes.
The basic answer to the previous question (copying classes not as reference type) was to use a memberwise clone method to avoid keeping links between the two classes.
Doing this on a class with only int values works, but this breaks apart as soon as I introduce arrays in the mix. See the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyClass
{
public int[] myNumber;
public MyClass ShallowCopy()
{
return (MyClass)this.MemberwiseClone();
}
}
public class Test : MonoBehaviour
{
Dictionary<string, MyClass> myDictionary1 = new Dictionary<string, MyClass>();
Dictionary<string, MyClass> myDictionary2 = new Dictionary<string, MyClass>();
void Start()
{
myDictionary1.Add("a", new MyClass() { myNumber = new int[] { 1, 1 } });
myDictionary1.Add("b", new MyClass() { myNumber = new int[] { 2, 2 } });
myDictionary2["b"] = myDictionary1["a"].ShallowCopy();
myDictionary2["b"].myNumber[0] = 3;
Debug.Log(myDictionary1["a"].myNumber[0]); //output 3, I'd want it to still be 1
}
}
I've tried implementing the ShallowCopy method (implemented in line 9 and used in line 25) and it doesn't work. I should implement a DeepCopy method, but I don't know how to formulate it applied to arrays.
My new DeepCopy function would be something like
public MyClass DeepCopy()
{
MyClass other = (MyClass)this.MemberwiseClone();
other.myNumber = ?????????????????????? //int[] deep copy
return other;
}
But I have no idea how to formulate a copy of the array. I've found a similar thread dealing with this, but I couldn't adapt the solution to my case.
Thanks in advance!
If you know that your array is going to be full of value types like int, or you have reference types and you want both arrays to refer to the same instance, you can use CopyTo
int[] copyTarget = new int[copyFrom.length];
copyFrom.CopyTo(copyTarget, 0);
If your array can/does have reference types in it, and you don't want the new array to reference the same instances, you will have to instead move through the elements doing a memberwise clone of each:
int[] copyTarget = new int[copyFrom.length];
for(int i = 0; i < copyTarget.Length; i++)
{
copyTarget[i] = copyFrom[i].MemberwiseClone();
}

Declare an array of queues [duplicate]

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
What is the language grammatical problem in my code?
I want to declare an array of queues. Is this the right way to declare and use them?
public static void Main(string[] args)
{
Queue<int>[] downBoolArray = new Queue<int>[8]();
downBoolArray[0].Enqueue(1);
}
Your first problem is a syntax error: new Queue<int>[8]() should be new Queue<int>[8].
Once declared with the correct syntax, when you attempt to use an element of the array (downBoolArray[0].Enqueue(1)) you will encounter a NullReferenceException because array elements initialise to their default values which in the case of a reference type is null.
You could instead initialise your array with non-null seed values using a single line of LINQ:
Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();
The arguments to Range specify that we need 8 'entries' in our sequence; the Select statement creates a new Queue<int> for each item; and the ToArray call outputs our sequence as an array.
You need to initialize each element in your array
void Main()
{
Queue<int>[] downBoolArray =new Queue<int>[10];
for (int i = 0; i < downBoolArray.Length; i++)
downBoolArray[i] = new Queue<int>();
downBoolArray[0].Enqueue(1);
}
You've created an array of null values.
What you want is something like this:
public static void Main(string[] args) {
var queues = new Queue<int>[8];
// Possibly some other stuff
// Initialise all values
for (var i = 0; i < queues.Length; i++) {
// Accounting for maybe already sporadically initialising values
queues[i] = (queues[i]) ?? new Queue<int>();
}
// Do whatever
}

Passing String Arrays to Functions? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?
using System;
class SalesPeeps {
string[] people = new string[8];
double[] salaries = new double[8];
static void Main() {
getInformation(people);
}
static void getInformation(string[] arr) {
int i = 0;
do {
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}
1) string[] people = new string[8];
is a field - not local variable. so when you say people - you are actually mean this.people but in static method there is no this.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
2) getInformation method use arr array as a parameter but do not reference to it. You can use people and make it static this will also fix problem from point 1.
I think this can be corrected this way:
class SalesPeeps
{
static string[] people = new string[8];
static double[] salaries = new double[8];
static void Main()
{
getInformation();
}
static void getInformation()
{
int i = 0;
do
{
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}
You cannot access non-static field people from static method Main. Change its declaration to:
static string[] people = new string[8];
Both of your variables are class members, which means they are the variables of the objects you can create from the class SalesPeeps.
Your method getInformation() is a static method and therefore only accepts static inputs.
A fix for this would be to make both of your variables static. Read more here.
Either way, you should be getting a error message from the compiler and this question should not be necessary as there are plenty of resources on this topic. Just check your compiler errors in your IDE and google them.

How can I append values in a C# array? [duplicate]

This question already has answers here:
Adding values to a C# array
(26 answers)
Add new item in existing array in c#.net
(20 answers)
Closed 5 years ago.
I need to add values to my array one integer value at a time, via user input.
I don't know how to ask it more clearly, but my goal is to define an integer array in Main(), then pass it to Interactive() where a user is supposed to enter 20 different ints and the program should add them to the array.
It would be tedious to continue defining new arguments for each object (like this):
int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]
because I am filling 20 array objects, surely there is an easier way?
Can someone help?
Here is the code I am working with:
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[20];
}
public static int[] Interactive(int[] args)
{
int[] ArrayOne = new int[20];
Write("\n Write an integer >>");
ArrayOne[0] = Convert.ToInt32(ReadLine());
foreach (int x in ArrayOne)
{
if (x != ArrayOne[0])
Write("\n Write another integer");
ArrayOne[x] = Convert.ToInt32(ReadLine());
WriteLine("\n {0}", ArrayOne[x]);
}
ReadLine();
return ArrayOne;
}
}
Try using a List. Unlike arrays their size can be dynamically changed.
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>();
numbers.add(1);
numbers.add(2);
}
}
Are you looking for this?
int[] intArray = Interactive(values here);
public static int[] Interactive(int[] args)
{
//TODO:
}

How to return multiple values in C# 7? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is it is possible to return multiple values from a method natively?
What do you mean by natively?
C# 7 has a new feature that lets you return more than one value from a method thanks to tuple types and tuple literals.
Take the following function for instance:
(string, string, string) MyCoolFunction() // tuple return type
{
//...
return (firstValue, secondValue, thirdValue);
}
Which can be used like this:
var values = MyCoolFunction();
var firstValue = values.Item1;
var secondValue = values.Item2;
var thirdValue = values.Item3;
Or by using deconstruction syntax
(string first, string second, string third) = MyCoolFunction();
//...
var (first, second, third) = MyCoolFunction(); //Implicitly Typed Variables
Take some time to check out the Documentation, they have some very good examples (this answer's one are based on them!).
You are looking for Tuples. This is an example:
static (int count, double sum) Tally(IEnumerable<double> values)
{
int count = 0;
double sum = 0.0;
foreach (var value in values)
{
count++;
sum += value;
}
return (count, sum);
}
...
var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");
Example stolen from http://www.thomaslevesque.com/2016/07/25/tuples-in-c-7/
You can also implement like this:
public class Program
{
public static void Main(string[] args)
{
var values=GetNumbers(6,2);
Console.Write(values);
}
static KeyValuePair<int,int> GetNumbers(int x,int y)
{
return new KeyValuePair<int,int>(x,y);
}
}

Categories