I am developing an application in C# with winforms. I am pretty good with C++ but very new to C# so please forgive my ignorance.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class obj
{
private int member;
public obj(int n)
{ member = n; }
}
obj[] obj_arr = new obj[10];
obj_arr[0] = new obj(4); // Problem Here
}
}
This is a very simplified example of what I am trying to do, but as you can see I would like to declare an array of user defined objects. The problem I am having is that when I try to initialize the individual array member the compiler gives me an error. Actually it gives several errors. obj_arr[0] is highlighted with an error saying that it is a field but is being used as a type. The = is also highlighted with an error that says = is invalid token in class, struct, or interface declaration. Finally obj(4) is highlighted with an error saying method must have a return type.
I am a little stumped here, any help would be greatly appreciated.
New Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
obj_arr[0] = new obj(4); // Problem Here
}
class obj
{
private int member;
public obj(int n)
{ member = n; }
}
obj[] obj_arr = new obj[10];
obj o1 = obj_arr[0];
}
You're trying to execute code within the class definition. Only member initialization con occur outside of methods. Move that code to to another method, or the constructor:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
obj_arr[0] = new obj(4); // Problem Here
o1 = obj_arr[0];
}
class obj
{
private int member;
public obj(int n)
{ member = n; }
}
obj[] obj_arr = new obj[10];
obj o1;
}
That should make all of the compiler errors go away (one syntax error is causing another).
Related
See fellows I have a problem and is that i think my code is in a loop
And before you answer "RePoST" I have visited all the other threads and i still did not hit with a solution
namespace Triangle_Proportions
{
public partial class Form1 : Form
{
public class Data : Form1
{
public static class Variables
{
public static int A;
public static int B;
public static int C;
public static int a;
public static int b;
public static int c;
}
public void Set_Variables()
{
Variables.A = label0A.Left;
Variables.B = label0B.Left;
Variables.C = label0C.Left;
Variables.a = label_a.Left;
Variables.b = label_b.Left;
Variables.c = label_c.Left;
}
}
public Form1()
{
InitializeComponent();
Data etc = new Data();
etc.Set_Variables();
}
}
}
This part of the code its only goal is to call Set_Variables(); after InitializeComponent();
I know I can solve this simply by just "quicking out" Variables and Set_Variables from Data but i want both to remain inside Data because is easier to look it up when searching this.
It doesn't have any syntax errors but every time I decide to call Set_Variables(); the program never opens
You have a recursion problem.
In the constructor of Form1 you instaniate a new class which is also inherited from Form1 which is calling the constructor again. See the problem?
Create a non static version:
public class Variables
{
public int A;
public int B;
}
And your Form:
public partial class Form1 : Form
{
private Variables _variables;
public Form1()
{
InitializeComponent();
_variables = new Variables
{
A = label0A.Left,
B = label0B.Left
};
}
}
I looked on another question similar to this but couldn't quite understand what they did to solve the problem.
I am simply passing a value into a public static int:
namespace ModNote
{
public partial class homeScreen : Form
{
public homeScreen()
{
InitializeComponent();
}
private void gamemodButton_Click(object sender, EventArgs e)
{
backgroundProgram.moduleNumber = 1;
this.Hide();
moduleScreen showForm = new moduleScreen();
showForm.Show();
}
and this is where this variable is initialized
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
}
#endregion
}
and here a picture of the error: http://puu.sh/opETJ/fb8152d164.png
Thankyou.
edit: initializing the string array causes this error, any problems with this array being initialized? (moduleArray)
namespace ModNote
{
#region // Setting up Variables
public class backgroundProgram
{
public static int moduleNumber;
public static string[] noteArray;
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
}
#endregion
}
If the exception is throw here:
public static string[] moduleArray = new string[7]
{ File.ReadAllText(#"ModulesFile\CGP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1005M.txt"),
File.ReadAllText(#"ModulesFile\CMP1123M.txt"),
File.ReadAllText(#"ModulesFile\CMP1124M.txt"),
File.ReadAllText(#"ModulesFile\CMP1125M.txt"),
File.ReadAllText(#"ModulesFile\CMP1127M.txt"),
File.ReadAllText(#"ModulesFile\CMP1129M.txt")
};
Then one of those lines is throwing an exception. There are all sorts of reasons for an exception to be thrown when reading from a file - security, not found, in use, etc.
I would suggest moving that logic to the static constructor so you can debug it to find the immediate problem, then add better error handling.
Another option is to not read all of that data in the static constructor and instead create an Initialize method or something. Exceptions in static constructors are difficult to handle in general.
I can't see anything other than an normal class initialized.
Here is the class, class Bet.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab_ADayAtTheRaces
{
public class Bet : Form1
{
public int Bets_Joe;
public int Bets_Bob;
public int Bets_Al;
public int Dog_Joe;
public int Dog_Bob;
public int Dog_Al;
public int Amount;
public int Dog;
public Guy Bettor;
public string GetDescription()
{
Amount = (int)numericUpDownBucksToBet.Value;
Dog = (int)numericUpDownDogToBetOn.Value;
//Bettor =
return Bettor + " placed a bet in the amount of " + Amount + " bucks on dog number " + Dog;
}
public int PayOut(int Winner)
{
return Winner;
}
public void MakeBets()
{
if (joeRadioButton.Checked == true)
{
Bets_Joe = (int)numericUpDownBucksToBet.Value;
Dog_Joe = (int)numericUpDownDogToBetOn.Value;
}
else if (bobRadioButton.Checked == true)
{
Bets_Bob = (int)numericUpDownBucksToBet.Value;
Dog_Bob = (int)numericUpDownDogToBetOn.Value;
}
else if (alRadioButton.Checked == true)
{
Bets_Al = (int)numericUpDownBucksToBet.Value;
Dog_Al = (int)numericUpDownDogToBetOn.Value;
}
}
}
}
Here is the code that throws the exception:
namespace Lab_ADayAtTheRaces
{
public partial class Form1 : Form
{
Bet bets = new Bet(); //**THIS LINE THROWS THE STACKOVERFLOW EXCEPTION**
Greyhound[] dogs = new Greyhound[3];
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
It wants me to say something more but I have nothing more to add so I'll just add some lines here and here.
Any help is muchly appriciated... thanks in advance
Kristjan
your Bet inherits from Form1, so Bet() will call to Form1(), and Form1() will again call to Bet() inside it -> again and again -> StackOverflow
Tip: We should never call the constructor of a class in its constructor or its class definition like this:
public class Form1 : Form {
public Form1(){
}
public Form1(string s){
}
public Form1 f = new Form1();//this will throw StackOverflowException
public Form1 f = new Form1("");//this will also throw StackOverflowException
//Form2 inherits from Form1
public Form2 f = new Form2(); //this will throw StackOverflowException
}
//or
public class Form1 : Form {
public Form1(){
Form1 f = new Form1();//This will throw stackoverflowexception
Form1 f = new Form1("");//This won't throw any exception
}
public Form1(string s){
}
}
When a class is initialized, all the members are initialized first before calling the constructor, hence the line Bet bets = new Bet(); is executed before initializing your Form1. So you have to avoid it. To initialize new Bet(), you should call it in some event so that the event will never be fired by calling the constructor, such as Load.
Bet bets;//Just declare it without initializing it
private void Form1_Load(object sender, EventArgs e){
bets = new Bet();
}
Why this part code don't running and show message "cannot be accessed with an instance reference qualify it with a type name instead"? Please about explain me.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
}
public class Report //my public class
{
public static double[] KwotaZ = new double[10];
public static double[] KwotaNa = new double[10];
public static string[] WalutaNa = new string[10];
public static string[] WalutaZ = new string[10];
public static int IlOperacji = 0;
}
private void button1_Click(object sender, EventArgs e)
{
Report raport2 = new Report(); //create new object class Report
raport2.KwotaZ[raport2.IlOperacji] = 213.3; //this wrong part code why???
Konwerter();
}
}
}
You're using static variables with an instance. there is only ever 1 static variable.
So you should either use it statically like so
Report.KwotaZ[Report.IlOperacji] = 213.3;
or define them as instance variables like so(without the static keyword)
public double[] KwotaZ = new double[10];
public int IlOperacji = 0;
KwotaZ and IlOperacji are static fields, so the syntax to access them is not instance.fieldName -- it is TypeName.fieldName, as in
Report.KwotaZ[Report.IlOperacji] = 213.3;
This will allow the program to compile, but it's probably not what you want. It's much more likely that you should make the static fields into instance properties:
public class Report //my public class
{
// Only showing two properties here; do the rest in the same manner
public double[] KwotaZ { get; set; }
public double[] KwotaNa = { get; set; }
public Report()
{
this.KwotaZ = new double[10];
this.KwotaNa = new double[10];
}
}
The problem is with the "static" keyword in your "Report" class. "static" means that there is only 1 copy of the variable. For example, even if you create 5 instances of the "Report" class, they will all have the same value for "KwotaZ".
What you probably want is to remove the "static" keyword. That way, each instance of "Report" will have its own version of the variables.
I am doing exercises in Head First C# book.
This code is supposed to be about encapsulation.
class DinnerParty
{
private int NumberOfPeople;
....
public void SetPartyOptions(int people, bool fancy) {
NumberOfPeople = people;
.....
}
public int GetNumberOfPeople() {
return NumberOfPeople;
}
}
In form1 class
public partial class Form1 : Form
{
DinnerParty dinnerParty;
public Form1()
{
InitializeComponent();
dinnerParty = new DinnerParty() {NumberOfPeople = 5 };
...
Is this suppose to work?
Visual Studio is showing me an error. (cannot access due to its protection level)
I am very new at this.
Thanks
That's becouse NumberOfPeople is private means that it can't be accessible from outside the class DinnerParty, so you need to make it public.
No that is not supposed to work. I can't see the book, so I can't comment on the context. However:
public int NumberOfPeopoe {get;set;}
Is a reasonable fix.
You could use the idea of a "Fluent interface" by writing something like:
class DinnerParty
{
private int NumberOfPeople;
....
public DinnerParty SetPartyOptions(int people, bool fancy) {
NumberOfPeople = people;
.....
return this; // Return own instance to allow for further accessing.
}
public int GetNumberOfPeople() {
return NumberOfPeople;
}
}
And then call it:
public partial class Form1 : Form
{
DinnerParty dinnerParty;
public Form1()
{
InitializeComponent();
dinnerParty = new DinnerParty().SetPartyOptions( 5, true );
...
NumberOfPeople is a private member and you can not use it out of the class dude
The NumberOfPeople is private, so it will not work. The best solution here is to create public property instead of private field or add constructor and initialize this field there.
You can't initialize a private field outside your scope (class).
Make it a property.
public int NumberOfPeople { get; set; }
and now, this will work
dinnerParty = new DinnerParty() { NumberOfPeople = 5 };