Static int main issue - c#

This is a Console Program
Scenario:
I have a many function in my c# code and is set to be Public and Private. And I have static int Main(string args[]) of course. In int Main i calling some function Public and Private and thats interupting the function when i debug that. It says if main was static so all function must be static, yet my code in function Public and Private must be have "that" function. If i change static int Main with my public int main, debug cant be done because int Main must be static.
First im saying i really sorry for giving a non-understable question
If that's so confusing understanding my scenario, see my Example Code Here
namespace Example
{
class Program
{
public class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
static int Main(string args[])
{
Foo();
}
}
}
That's my case
And with help from others i already build this
namespace Example
{
class Program
{
public static class ClassInPublic
{
public int Num;
public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
DeclaringInstance.Num = 35;
DeclaringInstance.Sentence = "Hello World";
Console.Write("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class");
}
public static int Main(string args[])
{
Foo();
}
}
}
Error sign is lower right now, the rest is the ClassInPublic
It says i cannot declare
cannot declare instance members in static class
May someone assist me to overcome this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example
{
class Program
{
public void foo()
{
Console.WriteLine("This is foo in Class Program");
}
static void fooStatic()
{
Console.WriteLine("This is Static foo");
}
static void Main(string[] args)
{
Program fooInstance = new Program();
fooStatic();
fooInstance.foo();
}
}
}
Here is a small example. Static functions are one per class. When you make public or private function they exist for each instance.
Edit:
Here is what I think you are trying to do:
namespace Example
{
class Program
{
public class ClassInPublic
{
static public int Num;
static public string Sentence;
}
ClassInPublic DeclaringInstance = new ClassInPublic();
private static void Foo()
{
ClassInPublic.Num = 35;
ClassInPublic.Sentence = "Hello World";
Console.WriteLine("This Private Function! And Assign Variable Value From ClassInPublic Variable");
}
private static void Foo2()
{
Console.Write("This Single Foo didnt have any Instance Class\n");
}
public static int Main(string[] args)
{
Foo();
return 0;
}
}
}

Related

How to call a non static method in the main?

class Program
{
static void Main(string[] args)
{
//I want to call the bird method here
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
How do I call bird in the main, I also tried to call the method from a object of the class but that didn't work
Does it even make sense to do this (I try to avoid static methods as much as possible).
If a method can be made static without changing the code, you should make it static. To answer your question though, you can create an instance of Program in your Main function and call the non-static methods through it.
class Program
{
static void Main(string[] args)
{
var p = new Program();
p.bird();
}
public void bird()
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}
Could do something like this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var p = new Program();
p.bird(p);
}
public void bird(Program program)
{
birdSpeech();
}
public void birdSpeech()
{
Console.WriteLine("Chirp Chirp");
}
}

Using delegates with non static methods in C#

Asking the same question as
Using delegates with non static methods [no picked answer]
so as to bring a closure to it.
So I use #Adam Marshall's solution, it works, but as soon as I start using it, i.e., Testit():
using System;
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;
public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private virtual void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
It started to give the followig Error:
A object reference is required for the non-static field, method, or property
You can test it out here .
How to fix it? (Please fix it if possible instead of directing me to other posts, I've read them but am not able to understand them) Thx.
Either everything has to be static or everything has to be instance. You're getting in trouble because you are mixing and matching.
Everything static:
using System;
public class TestClass
{
private delegate void TestDelegate();
static TestDelegate testDelegate; //<-- static
static TestClass() //<-- static
{
testDelegate = new TestDelegate(MyMethod);
}
public static void Testit()
{
testDelegate();
}
private static void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
Everything instanced:
using System;
public class TestClass
{
private delegate void TestDelegate();
TestDelegate testDelegate;
public TestClass()
{
testDelegate = new TestDelegate(MyMethod);
}
public void Testit()
{
testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var t = new TestClass();
t.Testit(); //<-- non-static
}
}
Output (same in both examples):
Hello World
Foobar
You could use action C# internal delegate. This way you do not have specify the delegate. Then in your static method you could new up your object.
using System;
public class TestClass
{
Action testDelegate;
public TestClass()
{
testDelegate = new Action(MyMethod);
}
public static void Testit()
{
TestClass ts = new TestClass();
ts.testDelegate();
}
private void MyMethod()
{
Console.WriteLine("Foobar");
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
TestClass.Testit();
}
}
Output:
Hello World
Foobar

Function referring to an instance created by other function C#

I have a question that may be silly, but I'm new to C#, so pardon my insolence. I am wondering whether it is possible for a function to refer to an instance, which has been created by another function.
I am including an exemplary code to illustrate what I mean:
class Program
{
static void Main(string[] args)
{
Instantiator.Instantiate();
Referent.Refer(instance);
Console.ReadLine();
}
}
public class Instance
{
public void OnInstantiated()
{
Console.WriteLine("I have been instantiated.");
}
public void OnReferred()
{
Console.WriteLine("I have been referred to.");
}
}
public class Instantiator
{
public static void Instantiate()
{
Instance instance = new Instance();
instance.OnInstantiated();
}
}
public class Referent
{
public static void Refer(Instance instance)
{
if(instance != null)
{
instance.OnReferred();
}
else
{
Console.WriteLine("No instance to refer to.");
}
}
}
What could I use to be able to refer to the "instance" instance (which is created by the Instantiator.Instantiate function) in the Referent.Refer function?
Thanks in advance for your pertinent comments!
Make Instantiator return the class when done
public class Instantiator
{
public static Instance Instantiate()
{
Instance instance = new Instance();
instance.OnInstantiated();
return instance;
}
}
class Program
{
static void Main(string[] args)
{
var instance = Instantiator.Instantiate();
Referent.Refer(instance);
Console.ReadLine();
}
}
The pattern Instantiate() is doing is often called the "Factory Pattern"
Another option you could use is the Singleton pattern. If you also need your instance to be only one, you can give the responsibility to create a new instance and return it afterwards to the class itself.
class Program
{
static void Main(string[] args)
{
Instance.Instantiate();
Referent.Refer(Instance.GetInstance());
Console.ReadLine();
}
}
public class Instance
{
private static Instance myInstance;
public void OnInstantiated()
{
Console.WriteLine("I have been instantiated.");
}
public void OnReferred()
{
Console.WriteLine("I have been referred to.");
}
public static void Instantiate()
{
myInstance = new Instance();
myInstance.OnInstantiated();
}
public static Instance GetInstance()
{
return myInstance;
}
}
public class Referent
{
public static void Refer(Instance instance)
{
if (instance != null)
{
instance.OnReferred();
}
else
{
Console.WriteLine("No instance to refer to.");
}
}
}

detect when "control flow" exits class

Assume I have a code:
class Module1 {
public static void Main(string[] args) {
Module1.level1();
}
public static void level1() {
Module1.level2();
}
public static void level2() {
Module2.level1();
}
}
[DetectWhenFlowExitsClass] // <-- note aspect
class Module2 {
public static void level1() {
Module2.level2();
}
public static void level2() {
Module2.level3();
}
public static void level3() {
throw new SystemException("oops");
}
}
After calling Main() I get a stacktrace:
Unhandled Exception: System.SystemException: oops
at Test.Module2.level3()
at Test.Module2.level2()
at Test.Module2.level1()
at Test.Module1.level2()
at Test.Module1.level1()
at Test.Module1.Main(String[] args)
Question
How to write aspect which detects moment when "control flow" exits code of class Module2?
That is, when Test.Module2.level1() finishes its work [here, due to exception].
Exist any shortcuts for this in PostSharp?
The most basic way would be to use OnMethodBoundaryAspect, which allows you to handle the method entry and method exit advices. You will need to count number of method of each particular class on the stack and when this count goes from 1 to 0, the control is leaving methods of the aspected class.
Here is the sample aspect code:
[Serializable]
public class DetectWhenFlowExitsClass : OnMethodBoundaryAspect
{
[ThreadStatic] private static Dictionary<Type, int> stackCounters;
private Type declaringType;
public override bool CompileTimeValidate(MethodBase method)
{
declaringType = method.DeclaringType;
return true;
}
private void EnsureStackCounters()
{
if (stackCounters == null)
stackCounters = new Dictionary<Type, int>();
}
public override void OnEntry(MethodExecutionArgs args)
{
EnsureStackCounters();
int counter;
stackCounters.TryGetValue(declaringType, out counter);
stackCounters[declaringType] = ++counter;
}
public override void OnExit(MethodExecutionArgs args)
{
EnsureStackCounters();
int counter;
stackCounters.TryGetValue(declaringType, out counter);
stackCounters[declaringType] = --counter;
if (counter == 0)
Console.WriteLine("Control leaving class {0}", declaringType.Name);
}
}
You will probably need to tinker with this aspect implementation a bit, but it works in basic situations.

"An object reference is required for the non-static field, method, or property" - why?

With this code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("saturnisko: {0}", UkladSloneczny.saturn.mass);
}
}
public class UkladSloneczny
{
private Saturn sat;
public UkladSloneczny(Saturn sat)
{
this.sat = sat;
}
public Saturn saturn
{
get { return this.sat; }
}
}
public class Saturn
{
private int masa;
public Saturn() { masa = 0; }
public int mass
{
get { return this.masa; }
}
}
Why I am getting error like so:
Error 1 An object reference is required for the non-static field, method, or property 'ConsoleApplication1.UkladSloneczny.saturn.get'
?
I assume you're getting it here: Console.WriteLine("saturnisko: {0}", UkladSloneczny.saturn.mass);
UkladSloneczny isn't a static class, so you can't call it like that. You need to either make it static or make a new instance of the class and then call yourClassInstance.saturn.mass.
If the class, method or property are not static then you have to instantiate the object in memory to be able to do anything with it, otherwise the object is null.
So either:
public static class UkladSloneczny
{
private static Saturn sat;
public UkladSloneczny(Saturn sat)
{
sat = sat;
}
public static Saturn saturn
{
get { return sat; }
}
}
OR
new UkladSloneczny().saturn.mass
You need to call it from an instance of UkladSloneczny, like this:
class Program
{
static void Main(string[] args)
{
Saturn saturn = new Saturn();
UkladSloneczny ukladSloneczny = new UkladSloneczny(saturn);
Console.WriteLine("saturnisko: {0}", ukladSloneczny.saturn.mass);
}
}
You need to make an object for UkladSloneczny:
class Program
{
static void Main(string[] args)
{
UkladSloneczny instance = new UkladSloneczny(new Saturn());
Console.WriteLine("saturnisko: {0}", instance.saturn.mass);
}
}
Or you can make the mass of saturn a static property:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("saturnisko: {0}", Saturn.mass);
}
}
public class Saturn
{
private static int masa = 0;
public Saturn() { }
public static int mass
{
get { return masa; }
}
}

Categories