Help with c# variables

  • Thread starter Thread starter Lambert Symth
  • Start date Start date
L

Lambert Symth

How can i use a variable from within a different function in which it was
not set.
Like the example.

using System;

namespace test
{
class class1
{
static void Main()
{
string name = "bob";
start();
}

static void start()
{
Console.WriteLine(name);
}
}
}
 
Lambert Symth said:
How can i use a variable from within a different function in which it was
not set.
Like the example.

using System;

namespace test
{
class class1
{
static void Main()
{
string name = "bob";
start();
}

static void start()
{
Console.WriteLine(name);
}
}
}

Currently the variable is a local variable - it's only available within
the method. You need to declare it as a static variable:

using System;

namespace test
{
class class1
{
static string name;

static void Main()
{
name = "bob";
start();
}

static void start()
{
Console.WriteLine(name);
}
}
}
 
You could pass it as a parameter like this

using System;

namespace test
{
class class1
{
static void Main()
{
string name = "bob";
start(name);
}

static void start(string name)
{
Console.WriteLine(name);
}
}
}
 
Lambert said:
How can i use a variable from within a different function in which it was
not set.
Like the example.

using System;

namespace test
{
class class1
{

public string Name=string.empty;
 
John Bailo said:
public string Name=string.empty;

That still won't compile (start is static) and even if it did, it would
print out an empty string rather than bob, as the local variable would
shadow the static/instance one.

In addition, your variable casing is somewhat odd (why change the OP's
variable name?) and variables shouldn't be public...
 
John Bailo said:
public string Name=string.empty;

Almost. If you get rid of the double declaration, this would likely work.
Replace this:

with this

(I'm guessing that this was your intent.)

Also, the variable could be declared 'private' instead. That would be
better data hiding.

To the OP: the best solution is to pass the variable as a parameter.
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
 
Back
Top