how to define a Global Structure in C#? - c#

I want to define a global structure in C# and use it in three separate subroutines. I have already created the structure but I don't know how to make it a global variable so I can use it in multiple sections of my code. Any help is appreciated.
public struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
static void Main(string[] args)
{
Simple s;
s.Position = 1;
s.Exists = false;
s.LastValue = 5.5;
}
So I want to use a Simple structure in two other routines in my code and possible pass it to different form (multiple usage of one variable).

The closest thing to "global" in C# is "static". Simply define the class and all members as static and it'll be accessible from anywhere the containing namespace is referenced. EDIT as Servy correctly points out, the class itself does not have to be static; however doing so forces all members to be static at compile-time. Also, static members can have any visibility, so you can have a private static field used by a public static property or method, and you can have an internal static class that won't be visible outside its home assembly. Just being static doesn't automatically make it wide open.
However, a better pattern might be the Singleton; you define a class that has one static instance of itself, that can then be passed around. The benefit is that you can still deal with the object as an instance class if you want to, but the same instance is available everywhere using a static getter. Here's some reading material: http://csharpindepth.com/Articles/General/Singleton.aspx

In your case it appears that you have a object as a local variable in your main method that you need to use in another method. The appropriate solution in this context is to add a parameter to that other method. Take a look at this example:
public class MyObject
{
public int Value;
}
public static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.Value = 42;
PrintObject(obj);
Console.WriteLine("Press any key to exit...");
Console.ReadKey(true);
}
public static void PrintObject(MyObject obj)
{
Console.WriteLine(obj.Value);
}

Related

How to run some code in a class at the time that it is defined?

In Python, I can have the equivalent of C# static members:
class MyClass:
i = 0 # This is like a C# static member
print(MyClass.i)
gives output
0
But maybe my static member needs to be calculated somehow. I can do:
class MyClass:
i = 0
i += 10
print(MyClass.i)
gives output
10
In practice, I'm writing a config class which needs to read a json file from disk, validate it, and then populate some static members. The closest thing to what I want to do in Python would look like:
class GlobalConfig:
with open('config.json', 'r') as f:
config_dict = json.read(f)
# Maybe do some validation here.
i = config_dict["i"]
a = config_dict["hello_world"]
Truth be told, I wouldn't really do this in Python, but I'm borrowing from C# in that everything needs to go in classes.
In practice in my C# code, I would have a GlobalConfig class in a Config.cs file and all my other files would have access to this.
But it seems I can't do anything other than declare/define members in the class body. How can I do the work of loading up and parsing my config file and have the result of that be accessible as static members to the rest of my program?
PS: I don't really want this to influence the answers I get in unless it has to, but FYI I am working with Unity.
Are you looking for static constructor?
public class MyClass {
private static int i = 0;
private static int j;
private static int loadJ(int value) {...}
// Static constructor will be called before the first MyClass call
static MyClass() {
// If you want to compute anything with static you can do it here
i += 10;
// you can call static methods here, address static fields and properties
j = loadJ(i);
}
}
An alternative to static constrcutors is some lazy-loading approach. In essence you just initialize your class when it is used in any way calling the loading-function internally:
public class MyClass
{
static int i;
private static int loadJ()
{
i = ReadValueFromJson();
}
public static DoSomething()
{
// load if not yet done
if(!loaded)
loadj();
// do the actual work
}
}
The advantage here is that you get more fine-grained controll about if or if not initialization should happen. Imagine some constant within your config-class that allways has the exact same value regardless of any initialization. The downsie is that you need to add this boilerplate to all the members that need loading.

How to declare variables and methods globally i.e. outside a class? [duplicate]

How do I declare a variable so that every class (*.cs) can access its content, without an instance reference?
In C# you cannot define true global variables (in the sense that they don't belong to any class).
This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:
public static class Globals
{
public const Int32 BUFFER_SIZE = 512; // Unmodifiable
public static String FILE_NAME = "Output.txt"; // Modifiable
public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}
You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):
String code = Globals.CODE_PREFIX + value.ToString();
In order to deal with different namespaces, you can either:
declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
insert the proper using directive for retrieving the variables from another namespace.
You can have static members if you want:
public static class MyStaticValues
{
public static bool MyStaticBool {get;set;}
}
First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.
Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,
Wrap all such Global variables into a single static class (for manageability).
Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.
The basic outline for such a class would be:
public class Globals
{
private static bool _expired;
public static bool Expired
{
get
{
// Reads are usually simple
return _expired;
}
set
{
// You can add logic here for race conditions,
// or other measurements
_expired = value;
}
}
// Perhaps extend this to have Read-Modify-Write static methods
// for data integrity during concurrency? Situational.
}
Usage from other classes (within same namespace)
// Read
bool areWeAlive = Globals.Expired;
// Write
// past deadline
Globals.Expired = true;
A useful feature for this is using static
As others have said, you have to create a class for your globals:
public static class Globals {
public const float PI = 3.14;
}
But you can import it like this in order to no longer write the class name in front of its static properties:
using static Globals;
[...]
Console.WriteLine("Pi is " + PI);

I need some help understanding the use of a private static variable

I already read up on a few posts here about private static, and I think I somehow got the idea, but I still have to ask for some help on clearing me up on this one.
Currently I am going through a class I didn't write, and I found this at the beginning private static string x.
I never came across private static, only public static for constants or similar things.
So now towards my question: What advantage does private static have?
I'm not sure if I'm correct, but as far as I understood, it's allowing the variable to only be accessible by methods of this class due to private.
The static part however tells me that that variable is unique and bound to the class, rather than to its objects, so assuming we have 5 instances of the class containing private static string x, all 5 instances will always have the same value when evaluating x.
Is this correct?
Yes. It is "global" variable for all objects of this class.
private static its useful for encapsulation of variables
for example java like enum
class MyEnum
{
private static List<MyEnum> _values;
public static Enumerable<MyEnum> Values {get { return _values.ToArray()}}
public static readonly FOO = new MyEnum('foo');
public static readonly BAR = new MyEnum('bar')
private MyEnum(string s)
{
//...
_values.Add(this);
}
}
as you can see we have _values variable which is not accessible from other class. But other class can obtain read-only copy via Values.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

I have searched about static variables in C#, but I am still not getting what its use is. Also, if I try to declare the variable inside the method it will not give me the permission to do this. Why?
I have seen some examples about the static variables. I've seen that we don't need to create an instance of the class to access the variable, but that is not enough to understand what its use is and when to use it.
Second thing
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
Console.WriteLine(book.myInt); // Shows error. Why does it show me error?
// Can't I access the static variable
// by making the instance of a class?
Console.ReadKey();
}
}
A static variable shares the value of it among all instances of the class.
Example without declaring it static:
public class Variable
{
public int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Explanation: If you look at the above example, I just declare the int variable. When I run this code the output will be 10 and 10. Its simple.
Now let's look at the static variable here; I am declaring the variable as a static.
Example with static variable:
public class Variable
{
public static int i = 5;
public void test()
{
i = i + 5;
Console.WriteLine(i);
}
}
public class Exercise
{
static void Main()
{
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Now when I run above code, the output will be 10 and 15. So the static variable value is shared among all instances of that class.
C# doesn't support static local variables (that is, variables that are declared in method scope).
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members#static-members
You can declare static fields (class members) though.
Reasoning: Static field is a state, shared with all instances of particular type. Hence, the scope of the static field is entire type. That's why you can't declare static instance variable (within a method) - method is a scope itself, and items declared in a method must be inaccessible over the method's border.
static variables are used when only one copy of the variable is required. so if you declare variable inside the method there is no use of such variable it's become local to function only..
example of static is
class myclass
{
public static int a = 0;
}
Variables declared static are commonly shared across all instances of a class.
Variables declared static are commonly shared across all instances of a class. When you create multiple instances of VariableTest class This variable permanent is shared across all of them. Thus, at any given point of time, there will be only one string value contained in the permanent variable.
Since there is only one copy of the variable available for all instances, the code this.permament will result in compilation errors because it can be recalled that this.variablename refers to the instance variable name. Thus, static variables are to be accessed directly, as indicated in the code.
Some "real world" examples for static variables:
building a class where you can reach hardcoded values for your application. Similar to an enumeration, but with more flexibility on the datatype.
public static class Enemies
{
public readonly static Guid Orc = new Guid("{937C145C-D432-4DE2-A08D-6AC6E7F2732C}");
}
The widely known singleton, this allows to control to have exactly one instance of a class. This is very useful if you want access to it in your whole application, but not pass it to every class just to allow this class to use it.
public sealed class TextureManager
{
private TextureManager() {}
public string LoadTexture(string aPath);
private static TextureManager sInstance = new TextureManager();
public static TextureManager Instance
{
get { return sInstance; }
}
}
and this is how you would call the texturemanager
TextureManager.Instance.LoadTexture("myImage.png");
About your last question:
You are refering to compiler error CS0176. I tried to find more infor about that, but could only find what the msdn had to say about it:
A static method, field, property, or event is callable on a class even
when no instance of the class has been created. If any instances of
the class are created, they cannot be used to access the static
member. Only one copy of static fields and events exists, and static
methods and properties can only access static fields and static
events.
Static variables are used when only one copy of it is required. Let me explain this with an example:
class circle
{
public float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * this._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.
class circle
{
static float _PI =3.14F;
public int Radius;
public funtionArea(int radius)
{
return this.radius * Circle._PI
}
}
class program
{
public static void main()
{
Circle c1 = new Cirle();
float area1 = c1.functionRaduis(5);
Circle c2 = new Cirle();
float area2 = c1.functionRaduis(6);
}
}
Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.
Static classes don't require you to create an object of that class/instantiate them, you can prefix the C# keyword static in front of the class name, to make it static.
Remember: we're not instantiating the Console class, String class, Array Class.
class Book
{
public static int myInt = 0;
}
public class Exercise
{
static void Main()
{
Book book = new Book();
//Use the class name directly to call the property myInt,
//don't use the object to access the value of property myInt
Console.WriteLine(Book.myInt);
Console.ReadKey();
}
}
The data members and function members that operate on the instance of the type
are called instance members. The int’s ToString method (for example) are examples of instance members. By default, members are instance members.
Data members and function members that don’t operate on the instance of the type, but rather on the type itself, must be marked as static. The Test.Main and Console.WriteLine methods are static methods. The Console class is actually a static class, which means all its members are static. You never actually create instances of a Console—one console is shared across the whole application.
In response to the "when to use it?" question:
I often use a static (class) variable to assign a unique instance ID to every instance of a class. I use the same code in every class, it is very simple:
//Instance ID ----------------------------------------
// Class variable holding the last assigned IID
private static int xID = 0;
// Lock to make threadsafe (can omit if single-threaded)
private static object xIDLock = new object();
// Private class method to return the next unique IID
// - accessible only to instances of the class
private static int NextIID()
{
lock (xIDLock) { return ++xID; }
}
// Public class method to report the last IID used
// (i.e. the number of instances created)
public static int LastIID() { return xID; }
// Instance readonly property containing the unique instance ID
public readonly int IID = NextIID();
//-----------------------------------------------------
This illustrates a couple of points about static variables and methods:
Static variables and methods are associated with the class, not any specific instance of the class.
A static method can be called in the constructor of an instance - in this case, the static method NextIID is used to initialize the readonly property IID, which is the unique ID for this instance.
I find this useful because I develop applications in which swarms of objects are used and it is good to be able to track how many have been created, and to track/query individual instances.
I also use class variables to track things like totals and averages of properties of the instances which can be reported in real time. I think the class is a good place to keep summary information about all the instances of the class.
Try calling it directly with class name Book.myInt
On comparison with session variables, static variables will have same value for all users considering i am using an application that is deployed in server. If two users accessing the same page of an application then the static variable will hold the latest value and the same value will be supplied to both the users unlike session variables that is different for each user. So, if you want something common and same for all users including the values that are supposed to be used along the application code then only use static.
You don't need to instantiate an object, because yau are going to use
a static variable:
Console.WriteLine(Book.myInt);
Static variable retains it's previous value until the program exit. Static is used by calling directly class_Name.Method() or class_Name.Property. No object reference is needed. The most popular use of static is C#'s Math class.
Math.Sin(), Math.Cos(), Math.Sqrt().

C# to C++ static class

I am porting some code from C# to C++. I am not sure how do I create a class like the static class in C#.
// in C#
public static temperatureClass{
private static int offset = 50;
private static Context context;
public static calculateTemperature(){
//use a;
//use context;
}
public static Context con{
set{
context = value;
}
}
}
int main() {
Context con1;
temperatureClass.con = con1; //con1 is a
temperatureClass.calculateTemperature();
}
Basically the temperatureClass is a utility class to perform calculation that no instances would be created.
I have a few questions:
Should the C++ version of calculateTemperature remain as static?
How could I initialize the int offset in C++ if I keep it as static because it is used by static calculateTempearture function?
Should I keep the con accessor as static in C++ as I need to set the context?
or more generally, what is the way of implementing an utility class like that in C++?
The C++ version could very well be a class containing only static members
The offset variable being of integral type, it can be initialized the same way as in C# if declared static (but you might want to add a const)
If context is static, the accessor must also be static as static member functions cannot access non-static member variables
Note that I don't think that this is good design. From my point of view, there isn't much sense in "whole static classes" in C++, and I'd rather use a set a free functions in a isolated namespace. If you choose the "static class" approach anyway, I'd recommend declaring the default constructor private to make it clear that the class has not point in being instantiated.
In C++, you don't need static classes, because you can have functions at namespace scope. In C#, static classes are needed because all functions have to be at class scope.
I'd do something like this:
// temp.h
namespace temperature {
void calculateTemperature(const Context& context);
}
// temp.cpp
namespace { // private stuff
int offset = 50;
}
namespace temperature {
void calculateTemperature(Context context){
//use a;
//use context;
}
}
// programm.cpp
#include "temp.h"
int main() {
Context con1;
temperature.calculateTemperature(con1);
}
Static classes in C# are simply classes that can not be instantiated, and contains only static method.
There's no explicit static class in C++, but you can simply achieve the same in C++ by hiding the constructors as private, and providing the public static methods.
By static initialization:
class temperatureClass {
private:
static int offset;
};
int temperatureClass::offset = 50;
You can leave it static, so you will follow the original as much it's possible.
Some air code, without letting it go through the compiler (so if there's an error, please tell me, I will fix it, but I think most of the stuff should have been translated correctly straightforward from C# to C++).
class temperatureClass
{
private:
static int offset = 50;
static Context context;
temperatureClass(){}; // avoid instantiation
public:
static void calculateTemperature()
{
//use a;
//use context;
}
static void SetCon(Context c)
{
context = c;
}
}; // dont forget semicolon in C++ :-)
int main()
{
Context con1;
temperatureClass::SetCon(con1);
temperatureClass::calculateTemperature();
}
(if this is a good design or not is another question, but that's independent of C# or C++)

Categories