I overwrite the variables 'arr[1]' and 'test' in setValues() function.
arr[1] is changed to 'BBB'
but test doesn't change to '222'
Output: BBB111
but it should be BBB222
Why string test doesn't get updated?
public class Program
{
static void Main(string[] args)
{
string[] arr = new string[10];
arr[1] = "AAA";
string test = "111";
setValues(arr, test);
int exit = -1;
while (exit < 0)
{
for (int i = 0; i < arr.Length; i++)
{
if (!String.IsNullOrEmpty(arr[i]))
{
Console.WriteLine(arr[i] + test);
}
}
}
}
private static void setValues(string[] arr, string test)
{
arr[1] = "BBB";
test = "222";
}
}
You need to pass that string by reference to be able to modify it in a method, you can do this by adding the ref keyword:
public class Program
{
static void Main(string[] args)
{
string[] arr = new string[10];
arr[1] = "AAA";
string test = "111";
setValues(arr, ref test);
int exit = -1;
while (exit < 0)
{
for (int i = 0; i < arr.Length; i++)
{
if (!String.IsNullOrEmpty(arr[i]))
{
Console.WriteLine(arr[i] + test);
}
}
}
}
private static void setValues(string[] arr, ref string test)
{
arr[1] = "BBB";
test = "222";
}
}
You are only altering the local reference to test in your setValues function. You would need to pass this variable by reference (ref)
private static void setValues(string[] arr, ref string test)
{
arr[1] = "BBB";
test = "222";
}
then call it like this:
setValues(arr, ref test);
It's because the test prameter in the setValues method is not marked as ref so it is changed only inside the method and the value does not get outside.
Because the array as object is passed by reference while the string is passed by value.
So, the function setValues() update the local copy of test, invisible to the caller, while update the ONLY instance of string[] arr, visible either to the caller than to the callee.
Paolo
The reason is variable scope. The variables referenced in your SetValues() method aren't the same variables referenced in Main.
There are 2 ways to resolve this, based on the need of the class:
As stated in other answers, pass the values by reference in the SetValues method (this preserves your code as-is):
private static void setValues(string[] arr, ref string test)
{
arr[1] = "BBB";
test = "222";
}
Move the variable declaration outside of the body of Main (This changes the scope of the variables to Class-level variables, which scopes them to the entire class, and possibly allows accessing them from other classes):
public class Program
{
static string[] arr = new string[10];
static string test = "111";
static void Main(string[] args)
{
arr[1] = "AAA";
and then call it by reference as well:
SetValues(arr, ref test);
Related
is it possible (in C#) to have different declarations of a static variable?
e.g.
I have a "static bool test = true".
Now I want a "static int interval" but it should depend on the test.
if (test)
{
static int interval = 1;
}
else
{
static int interval = 5;
}
because all variables aren't in methods and directly declared in a class I cant use any of this as it is...
thanks in advance!
There are two pretty similar ways to achieve that:
use the ternary within your assignement:
class MyClass
{
static bool test = true;
static int interval = (test ? 1 : 5)
}
use a static constructor:
class MyClass
{
static bool test = true;
static int interval;
static MyClass()
{
if(test) interval = 1;
else interval = 5;
}
}
I have a problem with the code:
namespace hello
{
public class Program
{
public static void Main(string[] args)
{
int xx = 5;
string[,] myArray = new string[1, 5];
if (xx > 4)
{
ResizeArray(ref myArray, 4, 5);
}
else
{
ResizeArray(ref myArray, 2, 5);
}
}
void ResizeArray(ref string[,] original, int rows, int cols)
{
string[,] newArray = new string[rows, cols];
Array.Copy(original, newArray, original.Length);
original = newArray;
}
}
}
I get the error message:
An object reference is required for the non-static field, method, or
property 'hello.Program.ResizeArray(ref string[,], int, int)'
Static members can't access non-static member without creating an instance.
You just need:
static void ResizeArray(ref string[,] original, int rows, int cols)
Thanks to the kind folks who answered my previous question from a few days ago, I now know how to pass arguments by reference:
static void Main()
{
int i = 0;
Add(ref i, 100);
// now i == 100
}
static void Add(ref int arg, int increment)
{
arg += increment;
}
But is there a way for me not to just pass i by reference, but actually store its location in another variable? By that I mean use i like I did in my example; affecting the original instance, but in a way that's permanently linked and not leaving scope.
I vaguely know that I could use a pointer to determine the location in unsafe context but I was wondering if I could do this without any of that, or if it is just recommended to use the unsafe method.
If you are using C# 7 you can use ref local and ref return to store an updateable reference to any field.
In this example I change the private field _privateField from 0 to 100 from outside Foo, the class in which it is defined, by returning it as a ref int and updating it by reference.
class Foo
{
private int _privateField = 0;
public ref int GetReference()
{
return ref _privateField;
}
public override string ToString()
{
return _privateField.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField = 100;
Console.WriteLine(foo);
}
}
Prior to that, you'd have to store the value in a field contained in an object, and pass around a reference to the object instead.
In this example I change the value from 0 to 100 from outside Foo, even though it is stored (indirectly) in a field that is private inside the Foo instance.
class ValueTypeReference<T> where T : struct
{
public T Value { get; set; }
}
class Foo
{
private ValueTypeReference<int> _privateField = new ValueTypeReference<int>{ Value = 0 };
public ValueTypeReference<int> GetReference()
{
return _privateField;
}
public override string ToString()
{
return _privateField.Value.ToString();
}
}
public class Program
{
public static void Main()
{
var foo = new Foo();
var referenceToPrivateField = foo.GetReference();
referenceToPrivateField.Value = 100;
Console.WriteLine(foo);
}
}
Output:
100
Well, if I udnerstood you correctly, you want the variable to have global scope, which can be achieved by putting variable as class field/property:
class Program
{
private static int _i;
static void Main()
{
_i = 0;
Add(100);
// now _i == 100
}
static void Add(int increment)
{
_i += 100;
}
}
I am trying to call a value from a method called GetInputstring from inside Main() method, and proceed to the next steps.
I am stuck regards to how I could get the value myInt and move along.
myInt (where it has two * around) inside Main() is where it gets the errors.
static void Main(string[] args)
{
GetInputstring(**myInt**);
if (**myInt** <= 0)
{
Write1(**myInt**);
}
else
{
Write2(**myInt**);
}
Console.ReadKey();
}
public int GetInputstring(int myInt)
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
return myInt;
}
static void Write1(int myInt)
{
while (myInt <= 0)
{
Console.WriteLine("{0}", myInt++);
}
}
static void Write2(int myInt)
{
while (myInt >= 0)
{
Console.WriteLine("{0}", myInt--);
}
}
MyInt is your parameter(the value you pass to your method) and it's not initialized. Further you don't catch your return value (which should be myInt)
You also need to make your methods static in order to call them from a static method or you create an instance of the class and invoke the method on it
That's how you'll get what you want:
static void Main(string[] args)
{
int myInt = GetInputstring(); //MyInt gets set with your return value
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring() //Deleted parameter because you don't need it.
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
int myInt = Int32.Parse(myInput);
return myInt;
}
You need to initialize your myInt variable and store it in the local or global scope. With this variable you will need to set it with the value you get from GetInputString() because you are not passing the int as a ref it will not be assigned in the method. You also need to make your methods static so they can be called from Main without creating an instance, Ex: public static int GetInputstring()
int myInt = 0;
myInt = GetInputstring(myInt);
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
Alternatively (And preferably), you could make GetInputString() assign the value because it dosen't need myInt to be passed as an parameter.
static void Main(string[] args)
{
int myInt = GetInputstring();
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring()
{
Console.Write("Please enter a number: ");
string myInput = Console.ReadLine();
return Int32.Parse(myInput);
}
I'm setting up multiple methods and wondering how to continue to pass one variable (The "top" variable) to different methods.
Main method:
public static void Main(string[] args)
{
int[] anArray = new int[5];
int top = -1;
PushPeek(anArray);
then I need to pass top to:
public static void PushPeek(int[] ar)
{
if (ar[ar.Length -1] == ar.Length -1)
{
//do nothing
}
else
{
top = top + 1;
Console.WriteLine(ar[top]);
}
}\
I know it involves something with get; set; but I don't know how, any help?
Pass it by reference:
public static void PushPeek(int[] ar, ref int top)
{
...
}
int[] anArray = new int[5];
int top = -1;
PushPeek(anArray, ref top);
All about properties: http://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx
Auto-implemented properties are awesome! http://msdn.microsoft.com/en-us/library/bb384054.aspx