I am having an issue passing properties from one class to another.
I'm getting an error saying that an object reference is required for all of the Game properties in the second class. They are highlighted at the bottom.
this is my first class (Game):
class Game
{
private string verb= "";
private string noun= "";
private string adjective= "";
private string panimal= "";
private string pnoun= "";
public string Verb
{
get {return verb; }
set {verb = value; }
}
public string Noun
{
get {return noun; }
set {noun = value; }
}
public string Adjective
{
get {return adjective;}
set {adjective = value; }
}
public string Panimal
{
get {return panimal; }
set {panimal = value; }
}
public string Pnoun
{
get {return pnoun; }
set {pnoun = value; }
}
public void InScreen()
{
Console.WriteLine("First, give me a past tense VERB: ");
Verb = Console.ReadLine();
Console.WriteLine("\nNow, give me a NOUN: ");
Noun = Console.ReadLine();
Console.WriteLine("\nNext, I will need an ADJECTIVE: ");
Adjective = Console.ReadLine();
Console.WriteLine("\nNow, I will need an ANIMAL(plural): ");
Panimal = Console.ReadLine();
Console.WriteLine("\nFinally, I neeed a plural NOUN: ");
Pnoun = Console.ReadLine();
}
My second class (InsertFunOOUI)
public void Poem()
{
Console.WriteLine("Humpty Dumpty " + **Game.Verb** + "on a " +
**Game.Noun**
);
Console.WriteLine("Humpty Dumpty had a " + **Game.Adjective** + "
fall"
);
}
...you get the picture.
Game is a Type. A class. You need to create an instance of it:
Game g = new Game();
and only then use:
g.Verb
etc.
You need to setup an instance of Game in order to use it, unless it you intended for it to be a static class.
Game game = new Game();
game.InScreen();
Something like that?
First create an instance of your game like #ispiro said. You need to do this once (in the main if possible). Then create an instance of your class poem. Use dependency injection and pass the properties of the game object in as parameters instead of the whole object if possible. I would even create a method inside your Poem class that handles the Console Output. Adapt this code to your liking:
public void main()
{
var game = new Game();
var poem = new Poem();
poem.Output(game.Verb, game.Adjective);
}
public class Poem()
{
public void Output(string verb, string adjective)
{
// your console writeline code
}
}
Related
public Program()
{
amount_bike = new ArrayList();
}
public void push(int value)
{
this.amount_bike.Add(value);
}
public int amount_bike_pop()
{
if (this.amount_bike.Count == 0)
{
return -100000;
}
int lastItem = (int)this.amount_bike[this.amount_bike.Count - 1];
this.amount_bike.RemoveAt(this.amount_bike.Count - 1);
return lastItem;
}
public static void Bike_status()
{
bool exit = false;
Program available = new Program();
available.push(0);
available.push(0);
available.push(50);
WriteLine("E-bike available for rent is : " + available.amount_bike_pop() + " bikes.");
WriteLine("Rented E-bike is : " + available.amount_bike_pop() + " bikes.");
WriteLine("Broke E-bike is : " + available.amount_bike_pop() + " bikes.");
WriteLine("\n");
WriteLine("Please enter a number: 1 is back to pervoius menu or 0 to Exit");
int input = Convert.ToInt32(ReadLine());
while (exit == false)
{
if (input == 1)
{
Clear();
exit = true;
continue;
}
else if (input == 0)
{
Clear();
Exit();
}
else
{
Clear();
Bike_status();
}
}
}
public static void Add_bike()
{
}
I study data structures and Algorithms. In this code, I keep the value in an ArrayList named "available" in the Bike_status method. I need to pass a value in an ArrayList to the Add_bike method. How do I pass a value from one method to another? Actually, I need to pass valus such as 50 to plus some number that I push in Console.ReadLine.
Try to slow down.at starting point of programming sometimes it's confusing.
How do I pass a value from one method to another?
The simple answer is easy ,you want something to use in the function then in your method(s) you create parameter and pass the things you want to it.
like
//edit method to get int value -> public static void Bike_status()
public static void Bike_status(int value)
//edit when to call
else
{
Clear();
Bike_status(input);//send int value in
}
But really, what is that do you really want to learn?
if it OOP? I recommend you study this
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/
To put it simply you has bicycle shop class separate from main program then use the method in that class
e.g.
//bicycle class
public class Bicycles{
public int ID {get;set;}
pulibc string status {get;set; }
public Bicycles(int p_id, string p_status)
{
ID = p_id;
status=p_status;
}
}
//bicycle shop class
public class BicyclesShop{
public List<Bicycle> available {get;set;} // class member
public BicyclesShop() // go search keyword "constructor"
{
available = new List<Bicycle> ();
}
//other method
public void Add_bike()
{
// I can access available object !
// do anything with this class member(s) !
}
public void Bike_status(int inputVal)
{
// do something with inputVal , change some properties?
}
//other methods
public int amount_bike_pop()
{
return available.Count();
}
public int amount_bike_broken_pop()
{
return available.Where(o=>o.status =="Broken").Count(); // go search linq
}
}
//To use in Main program method
BicyclesShop bs =new BicyclesShop();
bs.available.Add( new Bicycle(1 ,"OK") ); //add bicycle #1 in list
bs.available.Add( new Bicycle(2),"Broken" ); //add bicycle #2 in list
WriteLine("Broke E-bike is : " + bs.amount_bike_broken_pop() + " bikes.");
I have an string like "0000000"
and declared it in a class
public class Days_string
{
private string days= "0000000";
public string Days
{
get
{
return days;
}
set
{
days = value;
}
}
}
and I tried to change the string by clicking on 7 buttons
like this:
Days_string daystr = new Days_string();
var aStringBuilder = new StringBuilder(daystr.Days);
aStringBuilder.Remove(5, 1);
aStringBuilder.Insert(5, "1");
daystr.Days = aStringBuilder.ToString();
the output is 0000010
but it changed to 0000000 when I call it again
whats should i do?
Use static variable and static properties instead.and access the properties using className.properties name
public class Days_string
{
private static string days = "0000000";
public static string Days
{
get
{
return days;
}
set
{
days = value;
}
}
}
Even though the code is strange, but to solve your problem, you have at least two options:
Use an static variable :
private static string days = "0000000";
Or, create a global Days_string instance inside your form. By now, you are creating a new Days_string instance behind each button!
I am trying to learn C# and I am up to an example that uses a boolean. For the life of me I cant figure out why the program isnt noticing that I am trying to pass a value of true to the boolean. Here is the code in the Form.cs:
namespace WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
HappyBirthday birthdayMessage = new HappyBirthday();
string returnedMessage;
birthdayMessage.PresentCount = 5;
birthdayMessage.MyProperty = "Adam";
birthdayMessage.hasParty = true;
returnedMessage = birthdayMessage.MyProperty;
MessageBox.Show(returnedMessage);
}
}
}
Here is the Class that I created:
class HappyBirthday
{
//====================
// CLASS VARIABLES
//====================
private int numberOfPresents;
private string birthdayMessage;
private bool birthdayParty;
//===========================
// DEFAULT CONSTRUCTOR
//===========================
public HappyBirthday()
{
numberOfPresents = 0;
//birthdayParty = false;
}
//===========================
// METHOD
//===========================
private string getMessage(string givenName)
{
string theMessage;
theMessage = "Happy Birthday " + givenName + "\n";
theMessage += "Number of presents = ";
theMessage += numberOfPresents.ToString() + "\n";
if (birthdayParty == true)
{
theMessage += "Hope you enjoy the party!";
}
else
{
theMessage += "No party = sorry!";
}
return theMessage;
}
//================================
// READ AND WRITE PROPERTY
//================================
public string MyProperty
{
get { return birthdayMessage; }
set { birthdayMessage = getMessage(value); }
}
//================================
// WRITE-ONLY PROPERTY
//================================
public int PresentCount
{
set { numberOfPresents = value; }
}
public bool hasParty
{
set { birthdayParty = value; }
}
}
Now I set the initial value to false (even though if my understanding is correct that should be the default value), but when I try to set it = true, the program does not recognize it. Am I supposed to pass a boolean differently then I would a string or int?
You're setting MyProperty before you're setting hasParty. getMessage() is not being called every time MyProperty is polled.
The way MyProperty works is confusing, because the set and get deal with different values (you set the name, and then get the whole message, which is confusing). I'd replace it with a GivenName property and then make the GetMessage() (or expose it as a read-only property Message) public.
Also, you can make your code much simpler by using auto-properties (you can use private gets to keep the write-only behavior, though in the real world write-only properties are very rare, and you should probably just make them public like the sets). And since the default int value is 0, you don't need to specify your default constructor. Here's how the code looks now:
class HappyBirthday
{
public string Message
{
get
{
string theMessage;
theMessage = "Happy Birthday " + GivenName + "\n";
theMessage += "Number of presents = ";
theMessage += PresentCount.ToString() + "\n";
if (HasParty)
{
theMessage += "Hope you enjoy the party!";
}
else
{
theMessage += "No party = sorry!";
}
return theMessage;
}
}
public string GivenName { private get; set; }
public int PresentCount { private get; set; }
public bool HasParty { private get; set; }
}
So im trying to use the get / set properties on C# but I cant get my code to work ( it crashes my console app )
This is my textHandler.cs file as you can see the public static void method WriteInfo is using get / set properties but it crashes my app..
class TextHandler
{
public static void WriteInfo(String text)
{
var consoleText = new Text();
consoleText.text = text;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(consoleText);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteError(String text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteSuccess(String text)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(text);
Console.ForegroundColor = ConsoleColor.White;
}
public static void WriteText(String text, ConsoleColor color)
{
}
}
public class Text
{
public String text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
}
Here I call that method
TextHandler.WriteInfo("New client with version : " + message + " | current version : " + version);
If I remove that line the app doesnt crash anymore, dont know what Im doing wrong since I dont get any error.
Also if this is a bad method to do this please tell me I would like to improve
Thanks
The code that creates infinit recursion is:
public String text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
In set you assign this.text = value to itself, creating infinit recursion, so StackOverflow soon or later.
Seems that you do no need a field, so change your code to:
public String Text {get;set} //PROPERTIES ARE UPPERCASE BY MS STANDART
You need to separate the "backing" field from the public property:
public class Text
{
private string text;
public String TheText
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
}
In the above example, TheText is the a "badly named" public property and text is the backing field. At the moment, your code is addressing the same field for both, causing recursion. Usually the convention would be to have a capital property Text and a lowercase backing field text.
However, in your code you have named the class Text so it is confusing to address text.Text.
There is no need to create the "Text" class. Just pass the string to Console.WriteLine. Also, you didn't specify the nature of the application. This will work fine in a console app, but may not work for a web application or other app that is not bound to the SdtOut
So,
You are setting the into the property that is calling again the set method until you get a StackOverflow exception.
To avoid this try this
public class Text
{
string _text = null;
public String text
{
get
{
return this.text;
}
set
{
_text = value;
}
}
}
Or empty get set methods
public class Text
{
public string text { get; set; }
}
I've got something like this in my property/accessor method of a constructor for my program.
using System;
namespace BusinessTrips
{
public class Expense
{
private string paymentMethod;
public Expense()
{
}
public Expense(string pmtMthd)
{
paymentMethod = pmtMthd;
}
//This is where things get problematic
public string PaymentMethod
{
get
{
return paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(" "))
paymentMethod = "~~unspecified~~";
else paymentMethod = value;
}
}
}
}
When a new attribute is entered, for PaymentMethod, which is null or a space, this clearly does not work. Any ideas?
do you perhaps just need to replace string.IsNullOrWhiteSpace(" ") with string.IsNullOrWhiteSpace(value) ?
From your posted code, you need to call:
this.PaymentMethod = pmtMthd;
instead of
paymentMethod = pmtMthd;
The capital p will use your property instead of the string directly. This is why it's a good idea to use this. when accessing class variables. In this case, it's the capital not the this. that makes the difference, but I'd get into the habit of using this.
Jean-Barnard Pellerin's answer is correct.
But here is the full code, which I tested in LinqPad to show that it works.
public class Foo {
private string _paymentMethod = "~~unspecified~~";
public string PaymentMethod
{
get
{
return _paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(value))
_paymentMethod = "~~unspecified~~";
else _paymentMethod = value;
}
}
}
With a main of:
void Main()
{
var f = new Foo();
f.PaymentMethod = "";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = " ";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = "FooBar";
Console.WriteLine(f.PaymentMethod);
}
Output from console:
~~unspecified~~
~~unspecified~~
FooBar