This question already has answers here:
"Global variable" in Visual C#
(5 answers)
Closed 9 years ago.
I'm aware that global variables in most cases are not a good idea (especially in OOP), but I have a need where I need to create an array that can be read by any function or class within my application (basically, the array will store data that I'd only like to have to read once from my MySQL database).
It was suggested that I create a "Variables" class, but the problem I see with that is that I'd have to make a "public" (or global) instance of that class anyway, so creating a class doesn't really solve my problem from what I can see (I could be wrong, though).
How can I create a global variable array that can be seen by all classes and methods?
You want a static class.
public static class Global
{
public static string[] GlobalArray { get; set; }
static Global()
{
GlobalArray = //etc
}
}
which can be accessed from anywhere via :
var x = Global.GlobalArray;
You cannot create a global variable in C#, but you can create static classes with static properties.
public static class Global
{
public static string[] MyGlobalArray{ get; set;}
}
You need a singleton pattern:
public class Variables
{
private static Variables instance = new Variables();
public static Variables Instance
{
get
{
return instance;
}
}
public string[] GlobalArray { get; set; }
}
// Usage
var myGlobalArray = Variables.Instance.GlobalArray;
See also:
Implementing Singleton in C# (MSDN)
Implementing the Singleton Pattern in C# (C# in Depth)
Related
This question already has answers here:
Share a variable between two classes
(2 answers)
Closed 3 years ago.
I want to modify a variable in one class and iT to be accessed in another class in my program. How do i do this? and if there is, will the variable be updated in one class when i change it in another.
Most simple solution: define it as public static in Program class. Then access it from any class with Program.var_name.
You can follow the dependency injection pattern, there are some libraries to help you if you have a big project but if you just want to do something small you can hand craft it.
Create a class that will contain the shared variable
class SharedClass{
public int commonVar{get;set;} //not threadsafe
}
Every class that needs to have access to it it must get a reference to it through constructor.
class ConsumerOne{
SharedClass shared;
public ConsumerOne(SharedClass shared)
{
this.shared = shared;
}
public IncreaseThat(){
shared.commonVar++;
}
}
class ConsumerTwo{
SharedClass shared;
public ConsumerTwo(SharedClass shared)
{
this.shared = shared;
}
public DecreaseThat(){
shared.commonVar--;
}
}
And at your Program main you make the binding.
main(){
var shared = new SharedClass();
var one = new ConsumerOne(shared);
var two = new ConsumerTwo(shared);
one.IncreaseThat();
Console.WriteLine(shared.commonVar);
two.DecreaseThat();
Console.WriteLine(shared.commonVar);
}
That way you can tell what your classes are using and you will skip global variables.
This question already has answers here:
Workaround for inheriting from sealed derived class?
(1 answer)
How to workaround impossible inheritance from sealed class?
(2 answers)
The dream to inherit from a struct in c#
(3 answers)
Closed 3 years ago.
I am making a program that processes thousands of files. For each file I create a FileInfo instance, but I am missing some methods and properties that I need.
I wanted to make my own custom FileInfo class by inherting from FileInfo, but that class is sealed so I can't.
I considered making extension methods for FileInfo, but that seems ugly and it requires me to run the same code multiple times while processing.
So instead I came up with a custom class that 'wraps' the FileInfo class.
Here's a part of it:
class MyFileInfo
{
FileInfo _fileInfo;
// wrapper of existing property
public string Name { get { return _fileInfo.Name; } }
// custom property
public string NameWithoutExtension { get; private set; }
// custom property
public string Increment { get; private set; }
public MyFileInfo(string filePath)
{
_fileInfo = new FileInfo(filePath);
NameWithoutExtension = GetNameWithoutExtension();
Increment = GetIncrement();
}
private string GetNameWithoutExtension()
{
return _fileInfo.Name.Replace(_fileInfo.Extension, string.Empty);
}
private string GetIncrement()
{
return Regex.Match(NameWithoutExtension, #" #?\d{1,4}$").Value;
}
}
Now my question is: is this the best way to do this? How else could one work around not being able to inherit a sealed class?
You have done it almost right, The solution to your problem is exactly the use of decorator pattern.
The decorator pattern is a design pattern that allows the behavior to be
added to an individual object, either statically or dynamically,
without affecting the behavior of other objects from the same class.
Check these posts for more details:
1- UnderstandingplusandplusImplementingplusDecoratorp
2- benefiting-with-the-decorator-pattern
This question already has answers here:
Singleton Pattern for C# [closed]
(8 answers)
Closed 4 years ago.
I am learning Singleton design pattern in C#, and I have written below code in two ways, and I want to know Which one is the right way to create a Singleton class:
public sealed class TranslationHelper
{
// first way
private static readonly TranslationHelper translationHelper = new TranslationHelper();
// second way
public static readonly TranslationHelper translationHelpers = new TranslationHelper(); // Direct call
public static TranslationHelper GetTranslationHelper()
{
return translationHelper;
}
private TranslationHelper()
{
}
}
CALL:
TranslationHelper instance = TranslationHelper.GetTranslationHelper();
TranslationHelper ins = TranslationHelper.translationHelpers;
I am beginner so I am not sure if both methods are same. Please guide me.
If you are using .Net 4 or higher you can use the Lazy<T> type like this:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
By using this design pattern with a private constructor you are insuring that the class and it is only created at the time it is used. This is ensured because
It can only be called by itself so it does not get instantiated ahead of time.
The Lazy<T> keyword when used with the private static readonly lambda function now provides a visually clear way of lazily creating an instance of the class from within the function itself.
The public Singleton Instance property provides a way to access that singleton from outside the class.
This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 8 years ago.
here is two piece of class code one is for Singleton and other one is for static class. i like to understand in programming when one should use static class and when one should use Singleton class?
both are used to hold the global object as a result we can access those data from any where of the program when it is running. scope is broad for both....the life time of application.
1) i really do not find any article which can guide me when i should use static class and when Singleton class should be good choice. i have seen people manage db connection using Singleton class.
2) what is the main difference between Singleton class & static class ?
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
public static class TestStatic //: ITestSingleton
{
public static void doAction(string args)
{
Console.WriteLine("Test Static :: " + args);
}
}
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
Use singleton when you need a class that has only one instance, and you need to provide a global point of access to the instance
A singleton is basiccly an entry point to a single instance of a class. The instance of that class can be passed to another method as a reference.
A static class doesn't have this behaviour (only static methods are allowed).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In Windows application development using C# .NET, how do you make a global variable or global instance of a class, which can then be directly used by all other windows forms, e.g. form1, form2, etc.
You can create a static class and define a static variable inside it.
All the classes in your project can refer to it using MyGlobalVariables.GlobalVariable
public static class MyGlobalVariables
{
public static int GlobalVariable;
}
Create a public static class which holds the global variables
eg.
public static class GlobalValues
{
public static int UserId{get;set;}
}
Read more about C# Global Variable
Also I guess you should read about Classes and Structs
Create singleton class so that instace can be created once and used across application
public class Global
{
private static readonly Global instance = new Global();
public static Global Instance
{
get
{
return instance;
}
}
Global()
{
}
public string myproperty
{
get;set;
}
}
Usage:
Global.Instance.myproperty
Make it as a static variable and static class, e.g.
private static string foo = "this is static";
public static class Bar
{}