Variables in C#

Started by
5 comments, last by spectre223 14 years, 1 month ago
Hello. I'm trying to make a Windows Form Application calculator as a beginner project in C#. I've already gotten it to work, so now I'm trying to shrink the code. My problem is, I'm having a hard time figuring out how to make variables in one namespace usable in another namespace. Can someone help me?
Advertisement
Could you show us some code? Your question is not quite clear.

[Edited by - ernow on March 19, 2010 3:07:53 PM]
Variables can't live in namespaces in C# (there is no exposed concept of globals). You can make public static members of a class, however:
namespace N {  public class C {    public static int SomeVariable = 0;  }}

However, this might be an extremely bad idea depending on what you're actually trying to accomplish. Most likely you want to be passing instances back and forth between objects.

Why don't you explain what you're trying to actually accomplish by "sharing" these variables?
Here's what I currently have set up.


namespace calculator
{
public partial class CalculatorInterface : Form
{
public CalculatorInterface()
{
InitializeComponent();
}
static double decDev = 10;
static bool dec;
static int step = 1;
static int opperation;
static double number;
static double answer;

private void button1_Click(object sender, EventArgs e)
{
if (step != 3)
{
if (dec == false)
{
number = number * 10 + 1;
}
if (dec == true)
{
number = number + (1 / decDev);
decDev = decDev * 10;
}
textBox1.Text = "" + number + "";
}
}



I want to move the if statements somewhere else, and then reference them.
Quote:Original post by UltimaX
I didn't test this, but either one of these should work just fine.

*** Source Snippet Removed ***

C# does not allow global variables; the line defining xyz will not compile.

Also the statics are a hack. Try to rewrite it without them.

static members and functions are for things that belong to a class, not to an instance.

theTroll
Okay, I got it to work. Thanks guys.

This topic is closed to new replies.

Advertisement