Object is not bool or equals false - c#-7.0

I'm using C# 7.0 is type pattern. I'm trying to check if an object is not bool or the bool value equals false. However, the pattern I'm currently using with a bool type is:
if (obj is bool boolean && boolean)
{
/* I'm not doing anything here */
}
else
{
DoSomething();
}
Is there a way to invert this if expression using the same type pattern?

You can also use a constant pattern:
if (!(obj is true))
{
DoSomething();
}

Related

std::list<int> predicate call to function: Error C3867 function call missing argument list

I am using std::list's predicate to update the list based on predicate. But calling in the OnInitDialog() throws compilation error. My code is as follows:
The below is .h:
class CDlgWindow : public CDialog
{
private:
bool single_digit (const int &value);
int _days;
}
The below is .cpp:
CDlgWindow::CDlgWindow(CWnd* pParent, CString strInfo, int days) //ctor
{
_days = days;
//_strInfo = strInfo
}
bool CDlgWindow::single_digit(const int& value)
{
return (value >= _days);
}
BOOL CDlgWindow::OnInitDialog()
{
CDialog::OnInitDialog();
CenterWindow();
.
.
.
int numArr[] = {10,20,30,40};
int size = sizeof(numArr)/sizeof(numArr[0]);
std::list<int> numList (numArr, numArr+size);
numList.remove_if(single_digit); //Error C3867 here!
.
.
}
Complete error message:
Error C3867 function call missing argument list, use '&CDlgWindow::single_digit' to create a pointer to member.
I am trying to understand the functors concept. As I checked in C++11, we have lambdas for easier implementation. Please guide me to understand more on this issue. Thanks!
std::list's remove_if member needs a unary predicate (p) that operates on values (v). The expression p(v) must be valid. Which it isn't if p is a non-static class member (see repro).
There are two options:
Make the predicate (single_digit) a static class member:
class CDlgWindow : public CDialog
{
private:
static bool single_digit (const int &value);
// ...
}
Make the predicate a free function:
bool single_digit(int const& value) {
static int days_ = ...;
return (value >= days_);
}
If you go with option 1 you will have to make _days static as well, since a static member function cannot access non-static instance data. If _days is a compile-time constant, make sure to mark it const as well. That'll open up some compiler optimizations.
This is all hoping that things haven't significantly changed between C++98 and C++11. It's hard to find a C++98 compiler to verify this.

Flutter converting String to Boolean

I am having a String that i would like to convert to Boolean Below is how the string looks like
String isValid = "false";
The String isValid can either be true or false
Is there a way i can directly convert this String isValid to Boolean. I have tried Sample questions and solutions but they are just converting Strings which are hard coded, for example most of the answers are just when the string is true
On top of my head, you can create an extension method for string data-type for your own need with all sorts of requirements checks and custom exceptions to beautify your desired functionalities. Here is an example:
import 'package:test/expect.dart';
void main(List<String> args) {
String isValid = "true";
print(isValid.toBoolean());
}
extension on String {
bool toBoolean() {
print(this);
return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
? true
: (this.toLowerCase() == "false" || this.toLowerCase() == "0"
? false
: throwsUnsupportedError);
}
}
Here, in this example, I've created a variable named isValid in the main() method, which contains a string value. But, look closely at how I've parsed the string value to a bool value using the power with extension declared just a few lines below.
Same way, you can access the newly created string-extension method toBoolean() from anywhere. Keep in mind, if you're not in the same file where the toBoolean() extension is created, don't forget to import the proper reference.
Bonus tips:
You can also access toBoolean() like this,
bool alternateValidation = "true".toBoolean();
Happy coding 😊
This example can work for you, either if is false or true:
String isValid = "true";
bool newBoolValue = isValid.toLowerCase() != "false";
print(newBoolValue);
You can use extensions like this
bool toBoolean() {
String str = this!;
return str != '0' && str != 'false' && str != '';
}
First of All
You should make the string to lowercase to prevent check the string twice
then you can check if the string equal "true" or not and save the result to bool variable as below:
String isValidString = "false"; // the boolean inside string
bool isValid = isValidString.toLowerCase() == 'true'; // check if true after lowercase
print("isValid=$isValid"); // print the result
I opened a PR for this question, I believe that in the future it will be possible to do something native.
void main() {
print(bool.parse("true")); // true
print(bool.parse("false")); //false
print(bool.parse("TRUE")); // FormatException
print(bool.parse("FALSE")); //FormatException
print(bool.parse("True", caseSensitive: false)); // true
print(bool.parse("False", caseSensitive: false)); // false
if(bool.parse("true")){
//code..
}
}
Reference
https://github.com/dart-lang/sdk/pull/51026

set ignore case value in when expression on strings

I know how to check a string is in another string
like this code.
when (myString) {
in "FirstString" -> {
// some stuff
}
in "SecondString" -> {
// some stuff
}
else -> {
// some stuff
}
}
in keyword under the hood calls this method CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false)
the question is this :
is there any way that in this case i can set ignoreCase = true ?
You can declare an ad-hoc local operator function contains for strings before when:
fun main() {
operator fun String.contains(other: String): Boolean = this.contains(other, ignoreCase = true)
when(myString) {
in "firstString" -> ...
}
}
This way that function will be invoked for in operator instead of the one declared in the standard library because it's located in the closer scope.
Note, however, that this trick works only if the original contains function is an extension. If it's a member function, it cannot be overridden with an extension.
You can use toLowerCase() function here :
when (myString.toLowerCase()) {
in "firststring" -> {
// some stuff
}
in "secondstring" -> {
// some stuff
}
else -> {
// some stuff
}
}
For the cases of when, if they're variables toLowerCase() needs to be called on each of them. But, if they're constants, simple using lower case strings will work - "firststring", "secondstring"

How to Return Nil String in Go?

I have a function which returns a string under certain circumstances, namely when the program runs in Linux or MacOS, otherwise the return value should be nil in order to omit some OS-specific checks further in code.
func test() (response string) {
if runtime.GOOS != "linux" {
return nil
} else {
/* blablabla*/
}
}
however when I try to compile this code I get an error:
test.go:10:3: cannot use nil as type string in return argument.
If I return just an empty string like return "", I cannot compare this return value with nil further in code.
So the question is how to return a correct nil string value?
If you can't use "", return a pointer of type *string; or–since this is Go–you may declare multiple return values, such as: (response string, ok bool).
Using *string: return nil pointer when you don't have a "useful" string to return. When you do, assign it to a local variable, and return its address.
func test() (response *string) {
if runtime.GOOS != "linux" {
return nil
} else {
ret := "useful"
return &ret
}
}
Using multiple return values: when you have a useful string to return, return it with ok = true, e.g.:
return "useful", true
Otherwise:
return "", false
This is how it would look like:
func test() (response string, ok bool) {
if runtime.GOOS != "linux" {
return "", false
} else {
return "useful", true
}
}
At the caller, first check the ok return value. If that's true, you may use the string value. Otherwise, consider it useless.
Also see related questions:
How do I represent an Optional String in Go?
Alternatives for obtaining and returning a pointer to string: How do I do a literal *int64 in Go?
Go has built-in support for multiple return values:
This feature is used often in idiomatic Go, for example to return both result and error values from a function.
In your case it could be like this:
func test() (response string, err error) {
if runtime.GOOS != "linux" {
return "", nil
} else {
/* blablabla*/
}
}
And then:
response, err := test()
if err != nil {
// Error handling code
return;
}
// Normal code
If you want to ignore the error, simply use _:
response, _ := test()
// Normal code
Go allows multiple return types. So use this to your advantage and return an error or any other type. Check this out for more info: http://golangtutorials.blogspot.com/2011/06/return-values-from-go-functions.html?m=1

Is there a parsing of bool like int in Dart?

In Dart, there is a convenience method for converting a String to an int:
int i = int.parse('123');
Is there something similar for converting String to bool?
bool b = bool.parse('true');
Bool has no methods.
var val = 'True';
bool b = val.toLowerCase() == 'true';
should be easy enough.
With recent Dart versions with extension method support the code could be made look more like for int, num, float.
extension BoolParsing on String {
bool parseBool() {
return this.toLowerCase() == 'true';
}
}
void main() {
bool b = 'tRuE'.parseBool();
print('${b.runtimeType} - $b');
}
See also https://dart.dev/guides/language/extension-methods
To the comment from #remonh87
If you want exact 'false' parsing you can use
extension BoolParsing on String {
bool parseBool() {
if (this.toLowerCase() == 'true') {
return true;
} else if (this.toLowerCase() == 'false') {
return false;
}
throw '"$this" can not be parsed to boolean.';
}
}
No. Simply use:
String boolAsString;
bool b = boolAsString == 'true';
You cannot perform this operation as you describe bool.parse('true') because Dart SDK is a lightweight as possible.
Dart SDK is not so unified as, for example, NET Framework where all basic system types has the following unification.
IConvertible.ToBoolean
IConvertible.ToByte
IConvertible.ToChar
IConvertible.ToDateTime
IConvertible.ToDecimal
IConvertible.ToDouble
IConvertible.ToInt16
IConvertible.ToInt32
IConvertible.ToInt64
IConvertible.ToSByte
IConvertible.ToSingle
IConvertible.ToString
IConvertible.ToUInt16
IConvertible.ToUInt32
IConvertible.ToUInt64
Also these types has parse method, including Boolean type.
So you cannot to do this in unified way. Only by yourself.
Actually yes, there is!
It's as simple as
bool.fromEnvironment(strValue, defaultValue: defaultValue);
Keep in mind that you may need to do strValue.toLowerCase()

Resources