Class object being initialized outside the method is not recognized - object

I already found the issue and moved the class object inside one of the methods, so I guess I'm just kind of curious why an object such as this MyObject name = new MyObject(); is not recognized but this private static int intName works when initialized (declared) on top of the methods right after "class Program" or whatever your class is.

both should work. If you are accessing it from a static method you need to add static keyword to the object definition like below.
private static MyObject name = new MyObject();
if you are accessing the same from instance method
MyObject name = new MyObject();
is fine. I am assuming this was your problem

Related

Class name class variable = null - what does this line mean in Android?

I am having trouble understanding the meaning of the following code:
public class CustomListViewAndroidExample extends Activity {
ListView list;
CustomAdapter adapter;
public CustomListViewAndroidExample CustomListView = null; // What does this line mean?
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
Its instance of current activity you can use in oncreate like
CustomListView.addContentView(view, params);
It's just like an "ordinary" variable except that it's explicitly set to null when the class is created. It's no different in principal than the following line:
CustomListViewValuesArr = new ArrayList<ListModel>();
This isn't really any different than setting the value in the constructor or OnCreate method.
Note that, as with your other variables, you'll need to initialize this to something other than null in order to be able to use it.
It is slightly odd that it's public, though. I'd also recommend including explicit access modifiers in front of your other fields - it's a bad practice to omit them and rely on the defaults.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

non-static variable this cannot be referenced from a static context

I'm working with java me. I tried to switch to a displayable(form2) in Second.java from an okCommand in another displayble(form1) in First.java (see my previous question on that).
I got an error non-static method getForm2() cannot be referenced from a static context. I had to add the word static to form2 declaration and also at the getForm2 method in Second.java before it could work.
Problem now is that a backCommand in form2 can't switch back to form1 in First.java and it pops up the error non-static variable this cannot be referenced from a static context.
I paused and took some time to refresh myself on the language fundamentals on how the static keyword is used and I got to know that a static method is a class method and a non-static method is an instance method and that a non-static cannot call a static method unless an instance of the non-static method is created and also that a static method can't call a non-static method.
I'm really not understanding the implementation as I should, and I'd appreciate some clarification using my example above.
Here's the source below from Second.java the error is coming from form2.setCommandListener(this);
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(this);
}
return form2;
You have a static method, but are using this. But this doesn't exist. It would normally reference to an instance of the class, but you don't have one here.
If your method wasn't static and you instantiated an instance of this class then this would work.
e.g.
Second s = new Second();
Form f = s.getForm2(); // if this method wasn't static
Making that method static means little more than namespacing. There isn't an associated instance and no this.
There are couple options. First is to create a static instance of Second and use it in the getForm2:
//...
// static instance
private static Second instance = new Second(/* put constructor arguments here, if any */);
//...
public static Form getForm2() {
if (form2 == null) {
form2 = new Form("form");
form2.addCommand(getBackCommand());
form2.setCommandListener(instance); // --> replace "this" with "instance"
}
//...
From the issues you describe though, I would prefer another option - returning to design you had in previous question and use an instance of Second as an argument passed via constructor of First.
Your First.java would then have lines like:
//...
private final Second second; // instance needed for commandAction
//...
First(Second second) { // constructor with parameter
this.second = second; // save the parameter
//...
}
Then, commandAction method in First.java could use code like:
switchDisplayable(null, second.getSecondForm());
// instead of Second.getSecondForm()

How to create an override method using Mono.Cecil?

I'm using Mono.Cecil to generate an assembly that contains a derived class that overrides a specific method in an imported base class. The override method is an 'implicit' override. The problem is that I cannot figure out how to designate it as an override.
I'm using the following code to create the override method.
void CreateMethodOverride(TypeDefinition targetType,
TypeDefinition baseClass, string methodName, MethodInfo methodInfo)
{
// locate the matching base class method, which may
// reside in a different module
MethodDefinition baseMethod = baseClass
.Methods.First(method => method.Name.Equals(methodName));
MethodDefinition newMethod = targetType.Copy(methodInfo);
newMethod.Name = baseMethod.Name;
newMethod.Attributes = baseMethod.Attributes;
newMethod.ImplAttributes = baseMethod.ImplAttributes;
newMethod.SemanticsAttributes = baseMethod.SemanticsAttributes;
targetType.Methods.Add(newMethod);
}
It is my understanding that an implicit override must have the same signature as the inherited method. Using the above code, when I view the resulting method in Reflector, the base class and the derived class methods have the exact same signature, namely "public virtual void f(int param)".
I've tried removing the explicit "virtual" attribute, but then the derived method ends up as "public void f(int param)'.
How do I get the derived method to have the correct "public override void f(int param)" signature?
NOTE: I have an extension method ("TypeDefinition.Copy") that clones a MethodInfo and returns a MethodDefinition by importing all of the referenced types, etc.
In your base class, let's say you generate the following method:
public virtual void f(int);
You have to make sure that it has the flag IsVirtual set to true. You also have to make sure that it has the flag IsNewSlot = true, to make sure that it has a new slot in the virtual method table.
Now, for the overridden methods, you want to generate:
public override void f(int);
To do so, you also need to have the method to be IsVirtual, but also to tell it that it's not a new virtual method, but that it implicitly overrides another, so you have to make it .IsReuseSlot = true.
And because you're using implicit overriding, you also have to make sure both methods are .IsHideBySig = true.
With that all set, you should have a proper overriding method.
For the benefit of other readers, here is the final result obtained by following JB's answer:
void CreateMethodOverride(TypeDefinition targetType,
TypeDefinition baseClass, string methodName, MethodInfo methodInfo)
{
MethodDefinition baseMethod = baseClass
.Methods.First(method => method.Name.Equals(methodName));
MethodDefinition newMethod = targetType.Copy(methodInfo);
newMethod.Name = baseMethod.Name;
// Remove the 'NewSlot' attribute
newMethod.Attributes = baseMethod.Attributes & ~MethodAttributes.NewSlot;
// Add the 'ReuseSlot' attribute
newMethod.Attributes |= MethodAttributes.ReuseSlot;
newMethod.ImplAttributes = baseMethod.ImplAttributes;
newMethod.SemanticsAttributes = baseMethod.SemanticsAttributes;
targetType.Methods.Add(newMethod);
}

Variables declared in constructor conflicting with class properties

I'm creating a button in ActionScript by extending flash.display.SimpleButton
The button doesn't behave as expected, however, when I declare certain variables in the constructor which also happen to exist as properties in the SimpleButton class. They appear to conflict..
Why is this? Shouldn't the locally declared variables be allowed to co-exist with similarly named class properites?
Snippet below might better illustrate the issue:
public class MyButton extends SimpleButton{
public function MyButton(/*..*/){
var upState:ButtonDisplayState = new ButtonDisplayState(/*..*/));
var downState:ButtonDisplayState = new ButtonDisplayState(/*..*/);
var overState:ButtonDisplayState = new ButtonDisplayState(/*..*/);
var hitTestState:ButtonDisplayState = new ButtonDisplayState(/*..*/);
super(upState, overState, downState, hitTestState);
}
}
The API docs are here (look for upState for example): http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/SimpleButton.html#upState
Thanks,
Aodh.
You can't redeclare already existing variables, local or not. The only place where you can do something like this is method parameters, where you can have same parameter names as local / class variables.
Why don't you just pass in those states to the constructor directly like:
super(new ButtonDisplayState(/*..*/)), new ButtonDisplayState(/*..*/)), new ButtonDisplayState(/*..*/)), new ButtonDisplayState(/*..*/)));
or alternatively just set them directly after calling super(); like this:
upState = new ButtonDisplayState(/*..*/));
downState = new ButtonDisplayState(/*..*/);
overState = new ButtonDisplayState(/*..*/);
hitTestState = new ButtonDisplayState(/*..*/);

Resources