This question already has answers here:
An object reference is required to access non-static member
(2 answers)
Closed 4 years ago.
I apologise, I know this question has been asked a thousand times before by C# beginners (of which I am one), but all the answers I can find say I need to either instantiate the class, or make it static. My class is instantiated, and I am trying to access the instance. Can anyone take a look at my code and work out what is going wrong?
public class RocketSimMain {
public RocketShip test = new RocketShip ();
public static void Main() {
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested()) {
test.Move(); <- Object instance error here.
}
}
}
As you can see, I'm instantiating the class and accessing the instance. The only thing that works is instantiating the class inside the Main method, but then I'm not able to access it in other classes.
You have to make test static in order to use it from a static method (Main).
This problem arises because you are trying to call a non-static class from a static method.
To solve it you must either make them both non-static:
public RocketShip test = new RocketShip ();
public void Main()
{
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
or instantiate it locally within the method:
public static void Main()
{
RocketShip test = new RocketShip ();
... // Do some setup stuff here
//Run the game loop
while (!EndGameRequested())
{
test.Move(); <- Object instance error here.
}
}
Related
Hi I've modified some delegate tutorial code to experiment and I know there are prebuilt delegates available but without taking those into account.
I don't understand how the following works which I will break down:
class Program
{
static void Main(string[] args)
{
Human human1 = new Human(20);
BuffsProccessor buffsProccessor1 = new BuffsProccessor();
BuffsProccessor buffsProccessor2 = new BuffsProccessor();
BuffsCanAdd buffsCanAdd = new BuffsCanAdd();
BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
buffHandler += buffsCanAdd.AddIntelligenceBoost;
buffsProccessor1.ProcessBuffs(human1, buffHandler);
buffsProccessor2.ProcessBuffs(human1, buffHandler);
}
}
public class BuffsProccessor
{
public delegate void BuffHandler(Race race);
public void ProcessBuffs(Race race, BuffHandler buffHandler)
{
buffHandler(race);
race.ShowStats();
}
}
public class BuffsCanAdd
{
public void AddStrengthBoost(Race race)
{
System.Console.WriteLine("Adding strength boost");
}
public void AddIntelligenceBoost(Race race)
{
System.Console.WriteLine("Adding intelligence boost");
}
}
What I'm finding confusing is how come this line works like the class and delegate are static:
BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
the class and the delegate within the class are accessible without an instance of the BuffsProccessor class.
What is happening in memory when
BuffsProccessor.BuffHandler buffHandler = buffsCanAdd.AddStrengthBoost;
the buffHandler is there I'm finding this so confusing I'm struggling to form my question. Since the new keyword isn't being used how and where is it being stored in memory if it isn't in an instance of the BuffProccessorClass?
I hope this makes sense I can't find any delegate tutorials that answers this specific question.
What, do you mean, "without an instance of the BuffsProccessor class"? It's right there:
buffsCanAdd.AddStrengthBoost;
See that buffsCanAdd? That's your instance. If it were a static method you could just say AddStrengthBoost without the object before it.
The reason it works is that delegates don't just keep a reference to a method, they can also store a reference to the object to invoke the method on. This is mandatory for delegates to non instance methods, because you can't just invoke those methods on thin air.
As for your second question, there is a new involved, it's just that since C# 2, you can skip it and the compiler will put it for you. Before that, you had to do it by hand:
BuffsProccessor.BuffHandler buffHandler = new BuffsProccessor.BuffHandler(buffsCanAdd.AddStrengthBoost);
But now it's considered bad style.
We all know that we cannot create object of class having private constructor. So the question arises is how many instances of this class can be created .Please find a sample code below.
public class Test
{
public int val ;
private Test(int sent)
{
val=val +sent;
}
public static void Callme(int GetVal)
{
Test obj=new Test(GetVal);
Console.WriteLine(obj.val);
}
}
public class Program
{
public static void Main()
{
Test.Callme(10);
//Console.WriteLine(Test.val);
Test.Callme(20);
//Console.WriteLine(Test.val);
}
}
As per what I know It should create 2 object of the class. Need help understanding this.
We all know that we cannot create object of class having private constructor.
Well, that's not accurate. You can create an object (instance) of a class having only private constructors by using static members of that class, just like in the code in the question.
What you can't do is create an instances of that class from anywhere else in the code.
how many instances of this class can be created
In your code sample there are two instances of class Test.
I think what might be confusing you is you expected the second Console.WriteLine to print 30, but it printed 20. That is because public int val ; is an instance member. If it was a static member, than it would have printed 30
Maybe something like this is what you're looking for:
public static Test Callme(int GetVal)
{
Test obj = new Test(GetVal);
Console.WriteLine(obj.val);
return obj;
}
And then create new instances like:
Test test1 = Test.Callme(10);
Test test2 = Test.Callme(20);
This way you can easily access the members of each instance. E.g. test1.val
Callme method is a static method. Static methods does not require an objects instance to be called upon. They don't have the this (keyword) reference and can be called directly on the class. In your situation Test.CallMe(someValue). Note that there is no object instance involved here.
If CallMe was NOT a static method you would have needed an instance/object to call it. For example
Test ob = new Test();
ob.CallMe(someValue);
What your example illustrates is the use of private fields/methods.
When a method like the constructor or a filed is marked with the private keyword that method/field can only be called/accessed from within the declaring class.
This means that CallMe can access the constructor because CallMe is a member of the class and the constructor is a member of the class thus they both can access each other.
When a class has only one constructor and that constructor is private it effectively means that an instance of the class can only be created from within the class.
So in current example CallMe creates an instance of the class each time it's called.
If you call CallMe 2 times you'll create 2 instances of the class.
Because the method Callme is static it is instantiated by the system at some point before it is used and then remains in memory for future calls. There is only one copy of a static memeber of a class ever created regardless of how many instances of the class are created.
This question already has answers here:
What is the use of making constructor private in a class?
(23 answers)
Why do we need a private constructor?
(10 answers)
What is the need of private constructor in C#?
(12 answers)
Closed 4 years ago.
use of private constructor :
it cant able to create instance,
it cant be inherit,
it contain only static data members
without private constructor also i can able to access class with its static declaration and static data member when assign value like the below example
class Test
{
public static int x = 12;
public static int method()
{
return 13;
}
}
class Program
{
int resut1 = Test.x;
int resut2 = Test.method();
static void Main(string[] args)
{
}
}
so i have doubts as below
why should go to private constructor
what is the use of private constructor block
is we cant do anything inside of private constructor block
when it execute please explain clearly
thanks in advance
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static. For more information see Static Classes and Static Class Members.
Follow this https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors
A private constructor prevents the generic default constructor from being used.
The generic default constructor allows a class to be instantiated; while, a private constructor.
According to this microsoft doc, they are generally used to prevent people from instantiating classes that only have static members/functions.
How can I derive from a class through reflection? The following works for getting an existing instance and for creating a new instance of the class.
public class TreeViewSHWinstances {
[MenuItem("Reflect/CreateSHWinstances")]
static void Activate() {
Main();
}
static void Main() {
Assembly asm = typeof(UnityEditor.EditorWindow).Assembly;
Type wndType = asm.GetType ("UnityEditor.SceneHierarchyWindow");
// Grabs an existing instance if it exists and then sets the focus to it.
EditorWindow exstWnd = EditorWindow.GetWindow (wndType);
// Always create a new instance regardless if one already exists.
EditorWindow newWnd = (EditorWindow)Activator.CreateInstance (wndType);
}
}
This is what I actually want to do, but obviously the assembly is not yet loaded and when I have tried to acquire it form the above class I get an error that says it is not a Type even though I'm requesting wndType.
// THIS IS NOT INTENDED TO NOR DOES IT WORK.
public MySceneHierarchyWindow : UnityEditor.SceneHierarchyWindow {
}
My guess was to use Emit in some way, but I after experimenting with it I'm not sure it is the right direction.
This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 8 years ago.
Consider the following class:
public class Extractor
{
public IService service;
public Extractor(IService service)
{
this.service = service;
}
public void DoSth()
{
var sampleMethodInfo = this.service.GetMethodInfo();
var version = ExtractAvailableMethodVersion(sampleMethodInfo);
// other stuff
}
private int ExtractAvailableMethodVersion(MethodInfo methodInfo)
{
var regex = new Regex(MIGRATION_METHD_NAME_EXTRACT_VERSION);
var matcher = regex.Match(methodInfo.Name);
return Convert.ToInt32(matcher.Groups[1].Value);
}
}
Resharper hints to make ExtractAvailableMethodVersion static. So my question is - should I make static method everywhere it's possible (like in the example ablove)? Is any performance difference when calling static / non-static method in such a case? Or is it only "code-style rule" to make static method when not using instance members?
You don't make methods static just when possible, you do it when it makes sense, ie. what method does is not related to specific instance, but to a class in general.
Evaluate whether this is the case here, but you are not using current instance anywhere in the method, so above might be the case.