0

If we declare a global variable in module in vb.net, we can use that variable in anywhere in project.

How can we achieve same thing in C#.

Previously when we tried to convert a vb.net project to C#, we succeeded in removing the syntax error but we can't access global variable in a form.

I need some solution or guidance. Where I am making a mistake?

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
Sai Sherlekar
  • 1,804
  • 1
  • 17
  • 18
  • I think you are looking for something similar http://stackoverflow.com/questions/4751013/c-global-module – zk. Sep 21 '11 at 05:46

6 Answers6

3

In C# you can declare a static field.

public class Foo
{
   public static string value;
}

and use value field using ClassName.Member syntax anywhere.

Foo.value="Hello!";
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
3

You can approximate a VB.Net Module functionality by putting the variable inside of a static class:

public static class Foo
{
     public static string Bar { get; set; }
}

This will let you access it anywhere in the namespace via Foo.Bar.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

You may want to also consider using the Singleton Pattern. This keeps your variable initialization logic in a sensible place. Its also pretty easy to protect or keep track of changes to your variable.

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
1

You have to declare them as static

C# Global Variable

global variables in c#.net - Stack Oveflow

Community
  • 1
  • 1
Rami Alshareef
  • 7,015
  • 12
  • 47
  • 75
0

Should work the same. Make sure if is marked static. Or try using a static property in your module instead of a variable.

Bernesto
  • 1,368
  • 17
  • 19
0

You cannot declare public variable if it's value type such as int,string and etc.

But you can wrap it in struct for example

Gregory Nozik
  • 3,296
  • 3
  • 32
  • 47