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
  • 50,756
  • 12
  • 89
  • 148
Sai Sherlekar
  • 1,782
  • 1
  • 16
  • 17
  • 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
  • 92,042
  • 19
  • 143
  • 183
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
  • 539,124
  • 75
  • 1,126
  • 1,354
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
  • 50,756
  • 12
  • 89
  • 148
1

You have to declare them as static

C# Global Variable

global variables in c#.net - Stack Oveflow

Community
  • 1
  • 1
Rami Alshareef
  • 6,787
  • 11
  • 44
  • 74
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,135
  • 13
  • 18
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,186
  • 3
  • 31
  • 47