We help IT Professionals succeed at work.

Setting a boolean value in a class

jschmuff
jschmuff asked
on
Medium Priority
212 Views
Last Modified: 2010-04-15
How would I set a boolean value from the main program if the boolean is in a class example being bool CanCast = true/false?
Comment
Watch Question

Implement a property a follow.
class Sample {
  // private member
  private bool mCanCast = false;

  bool CanCast
 {
    get
    {
       return mCanCast;
    }
   set
   {
     mCanCast = value;
   }
 }

Author

Commented:
what would the main program look like that the user sets it to?
// Instantiate the class.
Sample Instance;
Get the user input from dialog or any other way you prefer.
Set the value  this way.

Instance.CanCast = ValueFromTheUser;

Also you could prefer to expose it from the class as a shared member in wich case you would not have to instantiate the class to access it.

Author

Commented:
im a little confused since it is either a true or false setting? can you explain a little more
Ok, maybe i do not get it...

If the main program mean put a setting in app.cfg so you would access this property with
Instance.CanCast = properties.settings.default.YourSetting.

If from the main program mean get the value from the user you would do as preceeding.

If this do not answer your question.  Please give more detail about it please.
Commented:
His variable ValueFromTheUser is going to be a bool, so it can only be true or false.

Essentially the same as either:

Instance.CanCast = true;

or...

Instance.CanCast = false;

depending on the value of the ValueFromTheUser variable.
That's it.  Very simple up to that point.

Author

Commented:
so I would accept normal user input whatever I want maybe throw in a if(answer == "true") { Instance.CanCast = true;}
exact;

Author

Commented:
I get an error:

Program.cs(65,17): error CS0029: Cannot implicitly convert type 'string' to 'bool'

this is why I typed for it


            Console.Write("Will you be a healer?(true or false): ");
            answer = Console.ReadLine();
            if (answer = "true")
            {
                character.Heal = true;
            }
            else
                character.Heal = false;

Open in new window

use == for the comparison
if(answer == "true")  or
for a safer way use answer.toupper() == "TRUE", Like this if the user input True or tRue, it will work

Commented:
You also have to make sure that your "answer" variable is of a string type.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.