Accessing variables from other class in console application c# - c#

I cannot seem to figure out the following:
For a school project i need to run a simple program. The program has to be a console application. But i need to have a few classes, from which i need to refference a variable from the main class.
class Program
{
public K[] ksmall = new K[number];
static void Main(string[] args)
{
//do somethings with ksmall
}
}
class K
{
//something
}
class A
{
public void SomethingElse()
{
//do something with ksmall
}
}
I hope my example makes sense. So anyway, how can i acces the ksmall from class A. When i start creating instances of Program, i get null references. is there any possible way to make both classes acces the same ksmall?

As ksmall is a non-static variable, so a static function (Main in your case) can't access it.
So, you can declare ksmall as static:
public static K[] ksmall = new K[number];
So now you can access ksmall from Main function as well as from other class functions as "Program.ksmall".

You should re-think about the architecture of your project, for example some OOP principles will give you more tools. I would recommend having your classes designed that you can either pass the object you want to share by a parameter in a constructor or in your methods. Another thing be careful with the encapsulation of your classes (private is by default, public anyone, protected inside the same namespace, private).
I hope this help you to get more understanding of the problem no the symptom.

Two ways to go about it.
First is that you could make a third, static class to hold ksmall (and any other variables you want to access from anywhere in the future)
class Program
{
public K[] ksmall = new K[number];
static void Main(string[] args)
{
VariableHolder.ksmall = new K[0];
}
}
public class K
{
//something
}
public class A
{
public void SomethingElse()
{
//do something with ksmall
}
}
public static class VariableHolder
{
public static K[] ksmall = new K[number];
}
The other option is the pass ksmall into the method within the class as a parameter.
class Program
{
public K[] ksmall = new K[number];
static void Main(string[] args)
{
A classAInstance = new A();
classAInstance.SomethingElse(ksmall);
}
}
class K
{
//something
}
class A
{
public void SomethingElse(K[] kSmall)
{
kSmall[1] = new K();
//do something with ksmall
}
}

You need to make the class K public.
public class K
{
//something
}

Related

Accessing public methods in same class requires an Instance?

I'm a newbie to C# so forgive this question but I'm confused: Why do I need an instance of class Program to access method Sandbox which is public and in the same class?
namespace GoogleTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Sandbox();
}
public void Sandbox()
{
...
}
}
}
public void Sandbox()
{
...
}
is the important part: This method is not marked static, so it is not callable on the class, but on instances of the class. If you want to be able to call it directly, you need
public static void Sandbox()
{
...
}
and can't use this.
Because you're trying to access it from within a static method, but Sandbox is an instance method.
If you make Sandbox static, this won't be required:
static void Main(string[] args)
{
Sandbox();
}
public static void Sandbox()
{
...
}
Note that it also doesn't have to be public - public allows it to be used by other classes and within other assemblies, but within Program, that's not required.
Static methods exist at the Class level, you can consider them Global functions. Any non static methods are instance level and just as the name implies you can only execute instance methods on an instance. So by instantiating the class you have created an instance and now can call any public method. In your example you could also call any private methods or constructors because you are creating the instance from with the class you are creating.

Using different versions of class with static method

I use some library which has class with static method.
namespace lib
{
public class libClass
{
...
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
}
}
I need to use two instances of this class in two different places of my program (in different namespaces). The problem is that this instances should be independent from each other (libClass.num can be different).
I'll be glad if you help me deal with the problem. Thank you for reading.
It's not quite clear why you are in this situation, ie. what you can and can not do.
Ideally, I would just create an instance of the class, and avoid the whole problem, but I assume there is some reason you can't or do not want to do this?
Otherwise the simplest and cleanest way to solve this might be to just make two copies of the class, and put one in each namespace, each with their own static variable.
I would strongly recomend giving the classes different names too, just to be clear and avoid confusion later.
Your final option is to look for a completely different solution. Hard to say without knowing more about your scenario, but if you really can't use an instance, then it seems like num should perhaps not be the responsibility of this class at all.
Obviously, you want to store and use num in some logical context/scope; You should ask yourself which other options (other than that class) you have for doing that within your scope (hope that was not too abstract ^^).
UPDATE:
I see what you mean now. I think you should be able to override the class however. Try something like this:
using VariousTesting;
namespace VariousTesting
{
public class LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
}
}
namespace VariousTesting2
{
public class SubLibClassA : LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
public static int GetNum()
{
return num;
}
}
}
namespace VariousTesting2
{
public class SubLibClassB : LibClass
{
public static int num;
public static void libMethod(int arg)
{
num = arg;
}
public static int GetNum()
{
return num;
}
}
}
You can test it as follows:
SubLibClassA.libMethod(1);
Console.WriteLine(SubLibClassA.GetNum()); // 1
SubLibClassB.libMethod(2);
Console.WriteLine(SubLibClassB.GetNum()); // 2
Console.WriteLine(SubLibClassA.GetNum()); // still 1! Yay! :D

Global Static Class with Objects

Ok, so I know you can't have objects in a static class but i need a class that i can hold objects that are accessible from different classes. I am making a dll that will provide extended functionality to another program so i can't just inherit or pass classes around either. if need be i can just maybe make the properties of each object i need to be in the static class which would work but not be as friendly as i would like. anyone have any other ideas on how to accomplish something like this?
Actually, you can have objects in a static class -- they just have to be static objects.
For instance:
public static class SharedObjects
{
private static MyClass obj = new MyClass();
public static MyClass GetObj()
{
return obj;
}
}
And from elsewhere in your program you can call instance methods/properties/etc.:
SharedObjects.GetObj().MyInstanceMethod();
One option is to have a class with the accessors methods accessing a static object (or objects). The other parts of your system can use the class either as static or as a non-static. Here is the code:
public class GlobalInformation {
public static GlobalInformation CreateInstance() {
// Factory method through GlobalInformmation.CreateInstance()
return new GlobalInformation();
}
public GlobalInformation() {
// Regular use through new GlobalInformation()
}
static GlobalInformation() {
// Static initializer called once before class is used.
// e.g. initialize values:
_aString = "The string value";
}
public string AccessAString {
get {
return _aString;
}
}
public Foo AccessAnObject() {
return _anObject;
}
private static string _aString;
private static readonly Foo _anObject = new Foo();
}
Other parts of your system would use it as follows. Option 1:
var globalInfo = GlobalInformation.CreateInstance();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();
Option 2:
var globalInfo = new GlobalInformation();
var aString = globalInfo.AssessAString;
var anObj = globalInfo.AccessAnObject();
Option 2 would be my preferred one (I'd remove the static factory method CreateInstance()) as you could change the implementation at any time including making (some of) the fields non-static. It would appear to be a regular class while sharing data.

Easiest way to re-use a function without instantiation a new class

I currently have a function that looks like this:
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}
I use this function in a lot of different projects, so I want it to be very reusable. So for now I have it in a .cs file, enclosed in a namespace and a class:
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
The problem with this is that to use this one function in a given project, I have to do something like
new LayoutTransformAnimation.LayoutAnims().AnimateLayoutTransform(mygrid);
Which just seems like a lot of work to reuse a single function. Is there any way to, at the very least, use the function without creating a new instance of the class? Similar to how we can Double.Parse() without creating a new double?
One option is to make it a normal static method. An alternative - if you're using C# 3.0 or higher - is to make it an extension method:
public static class AnimationExtensions
{
public static void AnimateLayoutTransform(this object controlToAnimate)
{
// Code
}
}
Then you can just write:
mygrid.AnimateLayoutTransform();
Can you specify the type of the control to animate any more precisely than "Object"? That would be nicer... for example, can you only really animate instances of UIElement? Maybe not... but if you can be more specific, it would be a good idea.
You could make it into a static method.
MSDN Example
I find it useful to have a static util class with static methods in them which can be used within the project namespace.
public static class YourUtilsClass
{
public static Void YourMethod()
{
//do your stuff
}
}
You can call it like so: YourUtilsClass.YourMethod()
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public static void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);

Is there any way for a static method to access all of the non-static instances of a class?

This is probably a dumb question but I'm going to ask it anyways... I am programing in C#.NET. I have a class that contains a non-static, instance EventHandler. Is it possible to trigger that EventHandler for every instance of the class that exists from a static method?? I know this is a long shot!
You can do this, but you'll need to create a static collection of all your objects:
public class Thing
{
public static List<Thing> _things = new List<Thing>();
public Thing()
{
_things.Add(this);
}
public static void SomeEventHandler(object value, EventHandler e)
{
foreach (Thing thing in _things)
{
// do something.
}
}
}
You'll want to watch out for accumulating too may "Things" . Make sure you remove them from the list when you don't need them anymore.
No, there isn't. Basically there's no way to find all instances of a class, unless you write your own code to do that.
EDIT: Intrigued as to why this is downvoted. Anyway, to add a bit more detail: you should avoid needing to do this. You could make your type implement IDisposable, then register against a static event handler in the constructor, and unregister in the Dispose method. Heck, you could even have a finalizer to do that for you, which will cost you performance but at least not leak if you fail to dispose of the instance.
All of these are somewhat grim options, however. It would be far better to try to redesign so as to avoid the requirement. Perhaps you can give us more information about what you're trying to do, and we can come up with a workaround?
I could be wrong in understanding what you mean, but it should be simple...
This is the main file
using System;
using IdeaClass;
namespace TestIdeas
{
class Program
{
static void Main(string[] args)
{
Ideas i = new Ideas();
Ideas.triggerMany();
Console.ReadLine();
}
}
}
Then there is the Ideas class:
using System;
namespace IdeaClass
{
public class Ideas
{
static OtherClass oc = new OtherClass();
public static void triggerMany()
{
oc.runThing("textual");
}
public Ideas()
{
Ideas.oc.ThingEvent += DoThingHandler;
}
public void DoThingHandler(string thing)
{
System.Console.WriteLine(thing);
}
}
}
And then the other class.
using System;
namespace IdeaClass
{
class OtherClass
{
public delegate void DoThing(string text);
public event DoThing ThingEvent;
public void runThing(string text)
{
if (ThingEvent != null)
{
ThingEvent(text);
}
}
}
}
It does cause unfortunate coupling between the class that raises the event and the class with the static call, but it seems to do what you want.
You can do like this :
public class MyClass{
private static List<MyClass> Instances = new List<MyClass>();
public MyClass(){
lock(typeof(MyClass)){
Instances.Add(this);
}
}}
After this you can do what ever you want with Instances.

Categories

Resources