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.
Related
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:
What fields can a nested class access of the class it's nested in?
(3 answers)
Closed 6 years ago.
What is the best way to access fields from a nested class?
class FirstClass
{
public int FirstClassField;
public FirstClass()
{
this.FirstClassField = 5;
}
class SecondNestedClass
{
int SecondClassField;
public SecondNestedClass()
{
FirstClassField = 6;
}
}
}
The error:
An object reference is required for the non-static field, method, or property 'FirstClass.FirstClassField'
The goal is to be able to use and modify FirstClass fields from the Nested class.
For my purposes, the first class is a form
public partial class MyForm : Form
And passing a reference of MyForm is not possible since it is readonly.
Any ideas?
The nested class is just a nested type, nothing like a nested instance. So if you create an instance of SecondNestedClass, there is no instance of FirstClass involved. So for which FirstClass instance do you want to set FirstClassField?
SecondNestedClass and FirstClass are completely different and independent types. FirstClassField is not a member of SecondNestedClass.
The only difference to non-nested types is that an instance of SecondNestedClass is allowed to access private fields of an instance of FirstClass. But you still need an instance at all to access its fields.
How to solve this depends on what you actually are trying to achieve. You could consider providing an instance of FirstClass to the constructor of SecondNestedClass:
public SecondNestedClass(FirstClass first)
{
first.FirstClassField = 6;
}
This question already has answers here:
How to instantiate an object with a private constructor in C#?
(4 answers)
Closed 7 years ago.
I want to access some of the private members of a class which has its constructor defined as private. How do I create the PrivateObject for such class so that I can access its private members ?
I tried something like this but I cannot instantiate the class "MyClass1" so I am not able to instantite the PrivateObject.
MyClass1 myClass = new MyClass1(); //gives compilation error
PrivateObject po = new PrivateObject(myClass); //gives compilation error
Is there any workaround for this ?
Class with private constructor can only create itself from its own static method. For example:
class MyClass1
{
private MyClass1()
{
}
public static MyClass1 CreateInstance()
{
return new MyClass1();
}
}
It's private members like fields or properties are always accessible only from inside of the class (unless you make some tricks with reflection). If the field is protected you can access it by deriving from this class. All other way it's by design created to restrict access to those fields and you should not try accessing them from the outside.
Edited: now I noticed you use PrivateObject class which is created to make reflection trickes mentioned above. So now you only need to create instance. You should check what is the designed way of initializing this object probably by some static method?
Or check this link for more hacks with reflaction and using Activator: http://www.ipreferjim.com/2011/08/c-instantiating-an-object-with-a-private-constructor/
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)
This question already has answers here:
What's the best way of accessing field in the enclosing class from the nested class?
(9 answers)
Closed 10 years ago.
i have two class i need to declare a variable common to both the classes..
In case of Nested classes i need to access the Outer class variable in the inner class
please give me a better way to do this in c#.
Sample code
Class A
{
int a;
Class B
{
// Need to access " a" here
}
}
Thanks in advance
First suggestion is to pass a reference to the Outer class to the Inner class on construction, so Inner class that then reference Outer class properties.
public Class Class_A
{
int a;
public Class Class_B
{
Class_A instance;
public Class_B(Class_A a_instance)
{
instance = a_instance;
}
void SomeMethod()
{
int someNumber = this.instance.a;
}
}
}
From your example, you probably need to pass a as a parameter to B in it's constructor - there's not way to access it otherwise. Having this as a 'child' class may not be a great design, however, but there's not enough information to really know either way.