Why my code Array value always contain "0" ?
static void Main(string[] args)
{
string Input = Console.ReadLine();
char[] Number = new char[3];
Util.SetNumber(Input,Number);
foreach (char digit in Number)
{
Console.WriteLine(digit);
}
Console.ReadKey();
}
This is the Class :
class Util
{
public static void SetNumber(string Input,char[] Number)
{
Number = Input.ToCharArray();
}
}
But if the "foreach" part i put it in Util.cs, it write the values..
Thank you before,
3 Answers 3
This is because you're not filling the array. In the method you're replacing the value (a reference to an array) held by the local variable Number with a completely new array. Such a change obviously cannot remain outside that method.
You could use Array.Copy or pass Number as ref:
Array.Copy(Input.ToCharArray(), Number, 3);
or
public static void SetNumber(string Input, ref char[] Number)
{
Number = Input.ToCharArray();
}
and then invoke it as follows:
Util.SetNumber(Input, ref Number);
Another (probably better) option here would be to use out instead of ref as out doesn't require you to initialise the variable you pass as parameter, so you don't need to do char [] Number = new char[3]; and can just use char [] Number; and pass it without further initialisation. That being said, when you use out you have to assign it a value in the method, so depending on how complex it's going to be that may or may not be feasible.
Here's a nice writeup on parameter passing in C# by Jon Skeet (You may have seen one or two answers by him on this site).
Minor side note: Maybe it's a deliberate decision, but your variable names do not adhere to the C# code guidelines which state that fields, parameters to methods and local variables have to use camelCase naming. PascalCase is reserved for types, methods and properties.
12 Comments
char * – changing that pointer will not change anything outside that method.Array.Copy which operates on the contents of the array. The second option with ref was suggested if they thought they'd have to use assignment for some reason.Better implementation would be (I think)
class Util
{
public static char[] SetNumber(string Input)
{
return Input.ToCharArray();
}
}
and
string Input = Console.ReadLine();
char[] Number = Util.SetNumber(Input);
foreach (char digit in Number)
{
Console.WriteLine(digit);
}
Console.ReadKey();
also in the original code the assignment char[] Number = new char[3]; can be remove since you create new one in your Util class
2 Comments
ToCharArray directly. Also the method name doesn't line up with what it does now anymore.You can get rid of the Util class altogether
string input = Console.ReadLine();
foreach (var digit in input.ToCharArray())
{
Console.WriteLine(digit);
}
Console.ReadKey();