Change The Default Value of Boolean - c#

I'm writing an application, where I have quite a lot Properties of Type Boolean defined:
private bool kajmak = true;
public bool Kajmak
{
get { return kajmak ; }
set { kajmak = value; FirePropertyChanged(() => Kajmak); }
}
As you see, I set kajmak to true at the beginning..-the reason is nonrelevant-. (You might know that the default value of a bool variable is false).
Now, is there a way, to change the default value of a bool to true? So I would write:
private bool kajmak; //kajmak = true
instead of
private bool kajmak = true;
What could I do to achieve this?

C Sharp 6.0 has introduced a nice new way to do this:
public bool YourBool { get; set; } = true;
This is equivalent to the old way of:
private bool _yourBool = true;
public bool YourBool
{
get { return _yourBool; }
set { _yourBool = value; }
}
see this article http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx

Because booleans are false by default, I use positive forms in my names, like IsInitialized, HasSomething etc. which I want to be false by default until I explicitly set them.
If you find you need something to be true by default, maybe you need to rename your variable so it makes more sense when the default is false.

In service:
public bool Kajmak { get; set; } = true;

No. There's no way to change the default value assigned by .NET. Your best bet is to either assign the appropriate default in the private member:
private book kajmak = false;
Or use the Constructor like you're supposed to and assign the class defaults there:
public class SomeClass
{
public SomeClass()
{
Kajmak = false;
}
public book Kajmak { get; set; }
}

No, there's no possibility to change the default value. If you could change the default-value, it wouldn't be the default anymore ;).
But to set the default-value to null, you could use this:
bool? kajmak;
But that's not what you want...

In the process of trying to do something similar, a colleague enlightened me to the bool? type. It can be true, false, or null, and does not object to being on the left side of such a comparator. This does not answer your question of how to default bool to true, but does solve your conceptual problem of wanting your variables to be definable as true by default.
I only post because this was the top result when I searched, and this information was helpful to me. Hopefully it will be to others who find this page.

You may create a class myBool that defaults to false and an implicit conversion from bool to your class.

Related

What does the following ambiguity errors mean?

Researched this error and some have said it's a bug but when I used some of their suggestions it didn't fix the problem. What should I do?
**Code
/// Indicates if the profiles has been added.
public Boolean _isNew
{
get { return _isNew; }
set { _isNew = value; }
}
/// Indicates if any of the fields in the class have been modified
public Boolean _isDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
//Gets and Sets delimiterChar
public Char _delimiterChar
{
get { return _delimiterChar; }
set { _delimiterChar = value;}
}
Error**
Ambiguity between 'ConsoleApplication3.ProfileClass.isNew'and 'ConsoleApplication3.ProfileClass.isNew
Ambiguity between 'ConsoleApplication3.ProfileClass.isDirty'and 'ConsoleApplication3.ProfileClass.isDirty
Ambiguity between 'ConsoleApplication3.ProfileClass._delimiterChar'and 'ConsoleApplication3.ProfileClass._delimiterChar
The code you have posted will cause recursion and eventual stackoverflow. You're trying to set property inside the property setter. You either need a backing field or automatic properties to achieve what you're doing. Something like:
private bool _isNew;
public Boolean IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
or
public Boolean IsNew {get; set;}
In C#, if you specify what you are getting and setting, you cannot use the same name as the property (self-reference issue). As of now, you are attempting to get and set a property to itself, which is not valid. Also a heads up about naming conventions, your public properties should not begin with an underscore, but should follow capital camel casing.
There are two answers to this, both equally valid depending on what you need to do.
METHOD 1: If you take out what it is getting and setting, C# can figure out that there is an implied field that is referenced by the IsNew property. This is essentially shorthand for METHOD 2.
public bool IsNew { get; set; } // shorthand way of creating a property
METHOD 2: Specify a field to get and set.
private bool _isNew; // the field
public bool IsNew { get => _isNew; set => _isNew = value; } // this is the property controlling access to _isNew
Read more information here: Shorthand Accessors and Mutators
Essentially, Use METHOD 1 by default if you don't need to perform any additional operations. However, if you need to provide additional functionality when getting or setting, then use METHOD 2 (I.E. look up the MVVM Pattern for an example https://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/)

Updated: Setting bool default value to true

I need to find a way to set the default value of ischecked to true, I am passing it as a parameter and I don't always set it.
ischecked is defined in my config files, I have multiple configs and in some it is defined and some it isn't. I won't get into why I use different configs. When it isn't define it is defaulted to false but I need it to be true.
function showSaveCardControl(ischecked) {
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
if it hasn't been defined I need the checkbox to be checked basically but since the default is false it is unchecked.
Update:
I am passing an xml element to a c# property. The xml would be where I set the value of ischecked but since I haven't set it somewhere either in the xml or once it has been turned into a c# property it is set to false. I am guessing it is set as the property tries to call that xml value.
I have tried setting the default using an attribute.
[XmlElement("EasyPaySaveCardControlChecked")]
[DefaultValue(true)]
public bool ischecked { get; set; }
I have tried setting it using a constructor.
public className()
{
ischecked = true;
}
I have also tried making all the bools nullable and the value is still being set to false
none of these solutions work and I have no idea why. no matter what I do the property is set to false, if it was set to undefined it would be fine but bools have to defaulted to false
Try something like this:
function showSaveCardControl(ischecked) {
if ('undefined' === typeof ischecked) ischecked = true;
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
this should do the trick :
function showSaveCardControl(ischecked) {
if(typeof ischecked == 'undefined')
ischecked = true;
$(".saveCardControl").slideDown().find("input").prop("checked", ischecked);
}
Assuming the property is part of a class then just set it's default value to true in the class constructor and it will be overwritten down the line if you have logic to set the value from the config.
public class LukesClass
{
public String whatever {get;set;}
public bool isChecked {get;set;}
public LukesClass()
{
isChecked = true;
}
}
Try using auto property initializers (C# 6.0 and higher):
public bool isRequired { get; set; } = true;
I had a single case where I needed an unspecified xml bool to import as true instead of false. The above code will result in isRequired being true when either the tags specify true, or when they do not exist. It will only be false when tags define it as false.

The property of user control always be false in C#?

I create a custom User Control which inherits from DataGridViewColumn.
Moreover, I added some properties in the control, but I can't modify them in design-time.
Even I set the default value as true, it's still false.
code:
public class ParaGridViewColumn : DataGridViewColumn
{
private bool _Necessary;
private bool _ReadOnlyEmpty;
[Description("Default cell status."), Category("Behavior"), DefaultValue(false)]
public bool Necessary { get { return _Necessary; } set { _Necessary = value;} }
[Description("When ReadOnly is true, clear value on the cell or not."), Category("Behavior"), DefaultValue(true)]
public bool ReadOnlyEmpty { get { return _ReadOnlyEmpty; } set { _ReadOnlyEmpty = value; }}
public ParaGridViewColumn()
{
this.CellTemplate = new ParaGridViewCell();
}
}
The new properties can shown on the window, but their default value are false.
I change them to true, entering and opening this window again, it's still false.
However, I can modify other properties regularly. It means I didn't lock this control.
Why is that?
Did I make something wrong?
Thanks a lot.
The first problem is with [DefaultValue(true)] for ReadOnlyEmpty while not setting the true value for it.
You have not set the default value for property to true.
In fact [DefaultValue(true)] help to CodeDomeSerizalizer to serialize value for this property if the property value is not equals to this default value.
You should set ReadOnlyEmpty= true in constructor or _ReadOnlyEmpty instead.
private bool _ReadOnlyEmpty=true;
The problem here is when you set property to true in property grid, when closing the form, serializer will not serialize true value, because you said it is default but you have not set it to true, so it will remain false.
The second problem is that if you want values persist, you should override Clone of base class and provide a clone copy that contains your custom properties.
public override object Clone()
{
ParaGridViewColumn column = (ParaGridViewColumn)base.Clone();
//Uncomment if you have ParaGridViewCell
//column.CellTemplate = (ParaGridViewCell)CellTemplate.Clone();
column.Necessary = this.Necessary;
column.ReadOnlyEmpty = this.ReadOnlyEmpty;
return column;
}
Well, I found the solution, losing an override clone function.
public override object Clone()
{
ParaGridViewColumn c = (ParaGridViewColumn)base.Clone();
c._Necessary = this._Necessary;
c._ReadOnlyEmpty = this._ReadOnlyEmpty;
return c;
}

Default value for bool in c#

public bool PrepaymentCalculating { get; set; }
So I declare a variable on one of my classes like that. I want this to default to 'null' and not false. Would I just need to make this a nullable boolean? Or is there a better way to do this?
Would I just need to make this a nullable boolean?
Yes.
Or is there a better way to do this?
No.
You can achieve this with
public bool? PrepaymentCalculating { get; set; }
try
public bool? PrepaymentCalculating { get; set; }
Here's a post on Nullable Types
public bool? PrepaymentCalculating { get; set; }
will make it nullable. Read about it here
If you want it to be null then you need to make it a nullable type.
Like everyone else said, but I thought I'd add, what's your purpose here? It's not often that I want to expose a nullable bool, since this means that everything that uses this property must account for a possible null value.
But sometimes I want to know if it's been initialized or not in a given context, and if not, then use a value from somewhere else (e.g. to cascade property values). In this case you might want to use a pattern like this:
public bool PrepaymentCalculating {
get {
if (_PrepaymentCalculating != null ) {
return (bool)_PrepaymentCalculating;
} else {
return somethingElse; // bool
}
}
set {
_PrepaymentCalculating = value;
}
} protected bool? _PrepaymentCalculating =null;
bool can't be null. The default is probably false (but don't quote me on that).
If you want it to be null, then yes you have to declare it as nullable.

How can I get XmlSerializer to encode bools as yes/no?

I'm sending xml to another program, which expects boolean flags as "yes" or "no", rather than "true" or "false".
I have a class defined like:
[XmlRoot()]
public class Foo {
public bool Bar { get; set; }
}
When I serialize it, my output looks like this:
<Foo><Bar>true</Bar></Foo>
But I would like it to be this:
<Foo><Bar>yes</Bar></Foo>
Can I do this at the time of serialization? I would prefer not to have to resort to this:
[XmlRoot()]
public class Foo {
[XmlIgnore()]
public bool Bar { get; set; }
[XmlElement("Bar")]
public string BarXml { get { return (Bar) ? "yes" : "no"; } }
}
Note that I also want to be able to deserialize this data back again.
Ok, I've been looking into this some more. Here's what I've come up with:
// use this instead of a bool, and it will serialize to "yes" or "no"
// minimal example, not very robust
public struct YesNo : IXmlSerializable {
// we're just wrapping a bool
private bool Value;
// allow implicit casts to/from bool
public static implicit operator bool(YesNo yn) {
return yn.Value;
}
public static implicit operator YesNo(bool b) {
return new YesNo() {Value = b};
}
// implement IXmlSerializable
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader) {
Value = (reader.ReadElementContentAsString() == "yes");
}
public void WriteXml(XmlWriter writer) {
writer.WriteString((Value) ? "yes" : "no");
}
}
Then I change my Foo class to this:
[XmlRoot()]
public class Foo {
public YesNo Bar { get; set; }
}
Note that because YesNo is implicitly castable to bool (and vice versa), you can still do this:
Foo foo = new Foo() { Bar = true; };
if ( foo.Bar ) {
// ... etc
In other words, you can treat it like a bool.
And w00t! It serializes to this:
<Foo><Bar>yes</Bar></Foo>
It also deserializes correctly.
There is probably some way to get my XmlSerializer to automatically cast any bools it encounters to YesNos as it goes - but I haven't found it yet. Anyone?
Very simple. Use a surrogate property. Apply XmlIgnore on the actual property. The surrogate is a string, and must use the XmlElement attribute that takes a element-name override. Specify the name of the actual property in the override. The surrogate property serializes differently based on the value of the actual property. You must also provide a setter for the Surrogate, and the setter should set the actual property appropriately, for whatever value it serialized. In other words it needs to go both ways.
Snip:
public class SomeType
{
[XmlElement]
public int IntValue;
[XmlIgnore]
public bool Value;
[XmlElement("Value")]
public string Value_Surrogate {
get { return (Value)? "Yes, definitely!":"Absolutely NOT!"; }
set { Value= (value=="Yes, definitely!"); }
}
}
click here for full compilable source example.
Making a bool value serialize as "yes" or "no" changes the data type from being a boolean at all. Instead, can you add a separate property which evaluates a boolean and returns "yes" or "no" as appropriate for it's data type? Maybe you could even force "yes" or "no" by making the return type be an enum which only specifies those values.
public YesOrNo DoYouLoveIt
{
get { return boolToEvaluate ? YesOrNo.Yes : YesOrNo.No; }
}
That might be overkill, but might answer your need. The only reason I bring up an enum for such a simple value is you'd be restricting the values vs. allowing any string.
I use the property method, but instead of checking to see if the string is equal to yes or no, I prefer to check if the string starts with (case insensitive) "YT1". This allows the file to contain true, True, t, T, y, Y, yes, Yes, 1, etc. all which will evaluate to true. While I can specify that false is false, False, f, F, n, N, no, No, 0, etc., anything that doesn't match the true still evaluates to false.
Your property example is probably the simplest way you could do it. If it helps, I believe you don't need to make it a public property, since the attribute implements ISerializable on the class behind your back. To enable deserialization, you should be able to just implement set { Bar = value == "yes"; }
#Blorgbeard:
If you have more then one of these YesNo classes in an object class,
make sure to read the entire element.
public void ReadXml(XmlReader reader)
{
string element = reader.ReadOuterXml();
int startIndex = element.IndexOf('>') + 1;
int length = element.LastIndexOf('<') - startIndex;
string text = (element.Substring(startIndex, length).ToLowerInvariant();
Value = (text == "yes");
}
Otherwise this might cause problems.
The ReadXml method must reconstitute your object using the information that was written by the WriteXml method.
When this method is called, the reader is positioned at the start of the element that wraps the information for your type. That is, just
before the start tag that indicates the beginning of a serialized
object. When this method returns, it must have read the entire element
from beginning to end, including all of its contents. Unlike the
WriteXml method, the framework does not handle the wrapper element
automatically. Your implementation must do so. Failing to observe
these positioning rules may cause code to generate unexpected runtime
exceptions or corrupt data.
What you're needing to do sounds more like a display issue. If your application allows, you will be better off keeping the data type as a boolean and displaying Yes/No in your user interface.

Categories