Default value for bool in c# - 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.

Related

Exclude complex property with reflection get properties [duplicate]

Is it possible when looking at a class' properties to detect if any of them is a reference type.
Take below as an example:
public class Client
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ProgrammeClient
{
public int Id { get; set; }
public bool IsActive { get; set; }
public IClient Client { get; set; }
}
ProgrammeClient: -
Id and IsActive are properties but Client is a reference type. Is there a way of detecting this?
Many thanks,
Kohan.
Addendum
The reason i ask is: I am using a mapper that checks types are the same before matching property names and copying the values. My hope is to detect classes and override the type matching and simply copy the classes properties if the THEY type match.
Well, it sounds like you may be trying to detect the difference between a value type and a reference type. You can find that out using Type.IsValueType... but be aware that value types can easily have properties too. (Think about DateTime for example.) Also, some types which you may want to regard as "not objects" are reference types - string being a prime example.
Another option would be to use Type.IsPrimitive - is that what you're looking for? If so, you should be aware that decimal, DateTime and string are not primitive types.
If you can describe exactly what makes a type an "object" in your way of thinking (or rather, in whatever way makes a semantic difference in what you're trying to do with your type). I suspect you don't currently have a very clear set of criteria - coming up with those criteria may well clarify other aspects of your current task, too.
You can use a little reflection to see if a property is a value type or a class type. Class is probably what you mean by "object". All types in .NET derive from the object type.
Client.GetType().IsClass
Or you can loop through all properties and see which are compound
foreach(var p in ProgrammeClient.GetType().GetProperties())
{
if(p.PropertyType.IsClass) Console.WriteLine("Found a class");
}
Check if the type is a string and check if it is a class.
public static bool IsNonStringClass(this Type type)
{
if (type == null || type == typeof(string))
return false;
return typeof(Type).IsClass;
}
All properties in your example return objects, as everything is an object in .NET; int and bool are objects. If you mean a reference type, as opposed to value types, then you can do the following:
foreach (PropertyInfo pi in typeof(Client).GetProperties()) {
if (pi.PropertyType.IsClass) {
// reference type
// DoMyFunkyStuff
}
}
You can enumerate the properties via Reflection, and check them:
bool ContainsOnlyValues() {
return typeof(ProgrammeClient).GetProperties().All(x => x.PropertyType.IsValueType);
}
The Type.IsvalueType property can reveal this.
Id.GetType().IsValueType
This will be True for Id, false for a class
If using TypeSupport nuget package you can simply do:
typeof(ProgrammeClient).GetExtendedType().IsReferenceType;
TypeSupport does inspection and provides deeper insight on the capabilities of a given type, handling things like strings, enums etc and makes it easier to code these types of things.

How to add and use null value in Enum?

See below enum contains two members: Test and Production
public enum OTA_HotelInvCountNotifRQTarget
{
Test,
Production,
}
I'm looking for the way to add and use Null value in above enum from code like :
inv.Target = OTA_HotelInvCountNotifRQTarget.Null; // Not allowed
Update:
I do not want to add extra NULL in above enum, I want to make this dynamic because the above enum is auto generated. and should be remain same.
Is there a way to achieve this in a method itself i.e without creating any Class or adding extra Enum value in enum?
like : inv.Target = OTA_HotelInvCountNotifRQTarget.Null;
How can I do this?
The underlining values of an enum are int which can't be assigned to null.
If you still want to do so:
Add Null as an option to the enum:
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Have your target a Nullable type:
Nullable<OTA_HotelInvCountNotifRQTarget> t = null;
//Or in a cleaner way:
OTA_HotelInvCountNotifRQTarget? t = null;
//And in your class:
public class YourType
{
public OTA_HotelInvCountNotifRQTarget? Target { get; set; }
}
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
also answewred here
How to set enum to null
Enum is enum. It value type and you can use
Nullable<OTA_HotelInvCountNotifRQTarget> or OTA_HotelInvCountNotifRQTarget? for represent "not set statement"
but if you still want user null as enum value try
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Or using the "?" Operator for the variable:
public OTA_HotelInvCountNotifRQTarget? Target;
You have to change the assignment to:
inv.Target = null;

How do I make this property nullable?

I have this line in C#, where incoming.icon is a property of a custom model, and dataItem.Icon is the property of a custom entity.
dataItem.Icon = incoming.icon;
The compiler complains because incoming.icon is nullable but dataItem.Icon isn't. Here is the dataItem 'Icon' property definition in the entity:
public Guid Icon {
get {
return ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set {
SetValue("Icon", value);
}
}
How do I make this property nullable in order to fix the error?
Like this:
public Guid? Icon
{
get
{
return (Guid?)ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set
{
SetValue("Icon", value.GetValueOrDefault());
}
}
Nullable is the struct that you're looking for.
public Nullable<Guid> Icon
This can be written in shorthand like so:
public Guid? Icon
If your design is that you don't want null values being set on dataItem.icon, then you might want to check incoming.icon and only get it's value if it exists instead. Like this:
if (incoming.icon.HasValue)
dataItem.Icon = incoming.icon.Value;

What is the difference between Nullable<bool> and bool? [duplicate]

This question already has answers here:
Is there any difference between type? and Nullable<type>?
(9 answers)
Closed 9 years ago.
When I reverse engineer my classes I get the following:
public Nullable<bool> Correct { get; set; }
public Nullable<bool> Response { get; set; }
I coded:
public bool? Correct { get; set; }
public bool? Response { get; set; }
Can someone tell me if there is any difference between these two. I have not seen the Nullable<bool> before and I'm not sure why it does not just create a "bool".
Note: I changed my coded to bool? in response to comments by Jon
"A Nullable can be assigned the values true false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined."
Nullable Types
Can someone tell me if there is any difference between these two. I
have not seen the Nullable before and I'm not sure why it does
not just create a "bool"
technically there is no difference in Nullable and bool?. Whatever you write they will compile down to Nullable in IL. so no difference. The ? is just C# compiler syntax.
why require system for Nullable
it is because it is used as a type. And type needs to be in a namespace.
But there is a difference in bool and bool?. As bool is a simple value type that cannot be assigned null value whereas you can assign value to bool?.
Nullable represents a value type that can be assigned null and it lies in the namespace System.
Further as it can be assigned null therefore you can check whether it has value or not like this
if(Correct.HasValue)
{
//do some work
}
Nullable<bool> and bool? are equivalent ("?" suffix is a syntactic sugar).
Nullable<bool> means that in addition to typical bool values: true and false,
there's a third value: null.
http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx
Null value could be useful if you work with uncertain values, e.g. in some
cases you can't tell if the instance is correct one or not, if any response
has been given; for instance in your case
// true - instance is correct
// false - instance is incorrect
// null - additional info required
public bool? Correct { get; set; }
// true - response was given
// false - no response
// null - say, the response is in the process
public bool? Response { get; set; }
Yes there is difference between Nullable<bool> and bool.
public Nullable<bool> Correct { get; set; } // can assign both true/false and null
Correct = null; //possible
whereas
in your case you can't have it
public bool Correct { get; set; } //can assign only true/false
Correct = null; //not possible
Maybe the previous guy who coded may not exposed to bool? dataType.
System.Nullable<bool> is equivalent to bool?
Update: There is no difference between Nullable<bool> and bool?
There is no difference.
Hint: Nullable<Nullable<bool>> n; // not allowed
Source msdn Nullable Types

Change The Default Value of Boolean

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.

Categories