0

What is exactly the equal of c++ extern int anything; in c# program? i have more than 10 class and i want to use a variable without change the value to default in each class. if i put this variable in one of this class, in other i change the value of variable but in other class variable value set to default but i need external or global variable to have fixed changed value in each class like c++ extern int anything; but in c#

MyJustWorking
  • 117
  • 2
  • 8
  • You don't need it in c#. – πάντα ῥεῖ Apr 10 '16 at 12:27
  • You need DllImport to make it work, you can use the C++ implementation directly, check this out - http://stackoverflow.com/questions/5110706/how-does-extern-work-in-c – Mrinal Kamboj Apr 10 '16 at 12:29
  • There is no such feature like extern in c#, C# is completely object oriented and you can't do any global declarations. The only way to do is to create a parent class for all your 10 classes and declare a static variable in that. Inherit all your 10 classes from the parent – iamrameshkumar Apr 10 '16 at 12:39

1 Answers1

1

To create a global variable in C# you will have to create a public static field or property in a class:

class Globals {

  public static int AnythingProperty { get; set; }

  public static int AnythingField;

}

If the Globals class only contains static members (which the name indicates) then you can change the class declaration to static class Globals.

From within any other class you can then access the property or field:

class SomeClass {

  public void SomeMethod() {
    Globals.AnythingProperty += 1;
    Globals.AnythingField = 2;
  }

}

Having global variables in your code will increase coupling and can lead to subtle errors and hard to understand code. Most often there are alternatives to using global variables but at least you know how to now.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256