Static fields question - c#

im trying to understand the get and set properties for fields, and run in to this issue, can somone explaine to me why i had to make the int X field Static to make this work?
using System;
namespace ConsoleApplication1
{
class Program
{
public static int X = 30;
public static void Main()
{
var cX = new testme();
cX.intX = 12;
Console.WriteLine(cX.intX);
cX.intX = X;
Console.WriteLine(cX.intX);
Console.ReadKey();
}
}
class testme
{
public int intX
{
get;
set;
}
}
}

Because you were using the field in a static context, in this case the method publicstaticvoid Main. Since your Program class just runs statically there is no instance and therefore you can't access any instance members.

because it is used in a static method

Since Main is static, you cannot access non-static instances from outside of it.

Related

Accessing variables from other class in console application 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
}

Error when trying to keep code inside of Main method

I am trying to teach myself this so I am sure this is obvious.
I am trying to create 2 classes that I can call instances of in Program/Main. One class is a string to double tryparse method and the other will just hold variables that will be used for many things.
My problem is I can only set Main up without error if the Main Method is only holding my new instance of class statements so I am exiting code immediately.
I will post the code to the Main. Newbie code and question, any help is much appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SetupMath
{
class Program
{
public static void Main(string[] args)
//Bringing in classes to inherit methods from
{
StringToDouble IntakeParse = new StringToDouble();
SetUpVar GuitAction = new SetUpVar();
}
// new instance of the StringToDouble class
// getting variable value "action" from string to double tryparse
public class StringToDouble
{
public string action { get; set; }
//converting "action" variable to "what"
public string What
{
get { return this.action; }
set { this.action = value; }
}
}
public class SetUpVar // new instance of the SetVar class
{
public string GuitAction { get; set; }
public string What { get; set; }
//Do something code
public void Work()
{
Console.WriteLine("Please enter a number", GuitAction);
What = Console.ReadLine();
Console.WriteLine("You entered: " + What);
}
}
}
}
You are writing StringToDouble and SetUpVar classes inside the Program class scope that's why they are visible only there. If you want your classes to be visible inside the whole namespace you should write them outside of Program class

How is the method called in static class

My code is as follows
class MyStaticClass
{
static MyStaticClass{};
public static readonly MyStaticClass Instance = CreateMe();
public static int GetSomeValue = GetValue();
private static int GetValue()
{
return 0;
}
private static MyStaticClass CreateMe()
{
Console.WriteLine("This method was called");
return new MyStaticClass();
}
}
public class Program
{
public static void Main()
{
int val=MyStaticClass.GetSomeValue;
}
}
O/p:
This method was called
When I call val why does the debugger accesses CreateMe method ? Is it that any static method I access it will access all the static methods in the class ?
The method CreateMe() is called because you are calling in when you create object Instance in the following statement.
public static readonly MyStaticClass Instance = CreateMe();
This is static object in your class and is created as you access the class which you did by MyStaticClass.GetSomeValue.
Dubugging the code will give you clear view of the order of the statements get executed. You can go through this detailed article on MSDN regarding debugging Debugger Roadmap
You have a static initializer for a static field. As part of program startup, all static fields are evaluated.
Edit: small clarification here:
The static fields in a particular class are evaluated in declaration order, but there in no particular order for which class has it's static fields initialized first.
Now, if you had a static property, that would be different.
MSDN link
Both fields have been initialized using the static methods. So, in that case, all the static methods will be evaluated.

Can a delegate be used to call a method of a class without instantiating it?

An interviewer asked me that he has got a heavy class with a number of methods.
He needs to have just one method as of now.
He asked me if Delegates in C# can help me calling that method without instantiating the class?
And he said Yes delegates can help us in this way.
I googled it. I tried running it on my VS but I guess I will need to initialize the class.
Have a look at this snippet -
public class HomeController : Controller
{
public ActionResult test()
{
NumberChanger nc1 = new NumberChanger( /*what to do here!
can i call sum method of class abc*/);
return View();
}
}
public delegate int NumberChanger(int n, int m);
public class abc
{
int a;
int b;
public int sum(int a, int b) {
return a + b;
}
}
If you need to use non-static method, probably you should use new NumberChanger(new abc().sum)
Have a try
You always need at least 1 instance to call an instance method.
But if you want to avoid creating lots of heavy objects, you could use a trick like this:
class TestClass
{
private static TestClass DummyInstance;
public static Action GetShowAsDelegate()
{
DummyInstance = DummyInstance ?? new TestClass();
return (DummyInstance.Show);
}
public void Show()
{
Console.WriteLine("It works!");
}
}
class Program
{
static void Main(string[] args)
{
var show = TestClass.GetShowAsDelegate();
show();
}
}
Your class stores a private static instance of itself, which is instantiated when the caller asks for a delegate version of Show(). It then uses that instance, so you don't need to create one externally each time. After the first call, anyone can run the Show method by getting a delegate, without the need to create any more instances.

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

Categories

Resources