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
{}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to use Java style polymorphism in C#. Is it possible?
Here is an example that does not compile
using System;
namespace HelloWorld
{
public class Program
{
public static void Main (string[] args)
{
Triangle triangle = new Triangle(2);
Square square = new Square(3);
printID(square);
}
public void printID(Shape s){
Console.WriteLine ("id is " + s.id);
}
}
public class Shape{
public int id;
}
public class Triangle: Shape{
float b;
float height;
float area(){
return b*height/2;
}
public Triangle(int k){
id=k;
}
}
public class Square: Shape{
float side;
float area(){
return side*side;
}
public Square(int k){
id=k;
}
}
}
The message is
MyClass.cs(11,4): error CS0120: An object reference is required to access non-static member `HelloWorld.Program.printID(HelloWorld.Shape)'
Thanks!
Error is not related to polymorphism - you are calling non-static method from static method Main. You should make printID static as well.
public static void printID(Shape s){
Console.WriteLine("id is " + s.id);
}
Also I suggest you to:
Stick with C# naming guidelines when you are writing C# code. Methods and properties should have PascalCase names.
Use properties instead of public fields
If any shape should have and id, consider to create public Shape(int id) constructor in base class and call that constructor from derived classes via : base(id)
Improve naming - if you are passing id, then call variable id instead of k.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can someone explain what is main difference between Instance and Static Members with real examples?
Static Members are run without using the implied "this" parameter which is the instance reference to the object that Instance Method was called from.
var number = Int32.TryParse("1234"); // Static member of Int32.
//Is not called using an object, it doesnt not need the 'this'
//because it doesn't change the data of the class.
string stringy = "asdfasdf";
char [] characters = stringy.ToCharArray();
//requires the strings data so it needs the instance stringy.
If the classes data is needed then you need an instance. If not you can make the method static so that it can be called at any time without an object.
Edit: I Initially read that as static methods. Static Data Members are completely different. When your program runs there is exactly one data object of that type allocated and is accessible via the class name not an instance of the class.
public class Classy
{
public static int number= 4;
public static void func() { }
// Other non-static fields and properties...
}
//mainline..
//
int n = Classy.number;
Classy.func(); // etc..
You don't create instances for static classes. You just call them using their type name.
For example.
public static StaticClass {
public static void StaticMethod(){}
}
To call the static method, you will just type this, StaticClass.StaticMethod().
When you create an object of a class, it is known as creating an instance of that class. You can only create instance of concrete classes).
For example
public class ConcreteClass {
public void RandomMethod(){}
}
To call RandomMethod, you will have to create an instance of the ConcreteClass by creating an object.
ConcreteClass abc = new ConcreteClass();
abc.RandomMethod();
Also note that, in a static class, all it's members will have to be static and this makes sense because, since you will not be instantiating the class, you should be able to call it's members directly. This is why in my static class example above, the method too is also static.
I hope this helps.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
An example:
class E
{
public static E e;
//...
};
What's the functionality of this or under which circumstances should we use this? Thanks.
One of usages can be to implement singleton (When you need a class that has only one instance, and you need to provide a global point of access to the instance): Implementing Signleton
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
A static variable cannot hold a reference to anything else that is declared in an instance, but rather a static variable/method belongs to the type instead of an instance of a type.
Consider this:
public class TestClass
{
private static string _testStaticString;
private string _testInstanceString;
public void TestClass()
{
_testStaticString = "Test"; //Works just fine
_testInstanceString = "Test";
TestStatic();
}
private static void TestStatic()
{
_testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
_testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
}
}
The many usages are so many it could fill books. As someone mentioned, the Singleton pattern makes use of it.
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)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm creating a simulator of ecosystems where species can be used to simulate various diseases, my problem is that I start using 4 species but if I need more ... I need more variables to store, my question is, Is there any way through Reflection to let me create dynamic variables during the execution of an event in my program? Thank you! i'm using Windows Presentation Foundation and C#
The normal way to handle this is to have a base class for your disease species and then use a collection to hold them all:
public abstract class DiseaseBase
{
public abstract void Spread();
}
public class Anthrax : DiseaseBase
{
public override void Spread()
{
GetPostedToPolitician();
}
}
public class BirdFlu : DiseaseBase
{
public override void Spread()
{
Cluck();
SneezeOnHuman();
}
}
public class SwineFlu : DiseaseBase
{
public override void Spread()
{
//roll in mud around other piggies
}
}
public class ManFlu : DiseaseBase
{
public override void Spread()
{
//this is not contagious
//lie in bed and complain
//get girlfriend to make chicken soup
//serve chicken soup with beer and baseball/football/[A-Za-z0-9]+Ball
}
}
public List<DiseaseBase> DiseaseCollection = new List<Disease>();
So everything gets stored in the collection as the base class (DiseaseBase), and with the appropriate use of abstract methods in the base and/or interfaces you can always handle each disease instance as the base object.