Using ternary operations to make my code cleaner [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have been doing some C# practice problems for a while and I want to start playing with ternary operations to make my code cleaner.
Here is my code:
public static string Bomb(string txt)
{
txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}
So basically if Bomb("xxxxxx") contains the string "bomb" it will return "Duck!!!" if not it will return "There is no bomb, relax."
But for some reason, this doesn't work and I can't figure out why.

You just need to add return
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") == true ? "Duck!!!" : "There is no bomb, relax.";
}

Your ternary operator looks OK, but you're missing a return statement from the function. Also note that Contains returns a boolean, so the == true is redundant:
So I have been doing some c# practice problems for a while and I want to start playing with ternary operations to make my code cleaner.
Here is my code:
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}

you missed the return part in the function
public static string Bomb(string txt)
{
return txt.ToLower().Contains("bomb") ? "Duck!!!" : "There is no bomb, relax.";
}

Related

using strings inside if statement throw error "Operator '||' cannot be applied to operands string and string" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Hi my c# is not what it used to be and have just come back after using java script for a while.
Essentially I am just trying to do a simple if statement using index of arrays but I receive the error message.
"Operator '||' cannot be applied to operands string and string"
How come this is not allowed as it essentially becoming a bool.
string[] userCustomAnswerArray = {"It needs to be reaplaced", "This could be improved", "I struggle to see this"};
int customResponseindex = rand.Next(0, 3);
string[] questionResponseArray = { "Yes", "No but not a problem", userCustomAnswerArray[customResponseindex] };
int questionResponseIndex = rand.Next(0, 3);
string userAnswer = questionResponseArray[questionResponseIndex];
if (userAnswer = questionResponseArray[0] || userAnswer = questionResponseArray[1])
{
}
Thanks for your help !!!!
userAnswer = questionResponseArray[0] is incorrect.
= is the assignment operator while == is the equality operator

Autodesk guide project two "a namespace cannot directly contain members from" [duplicate]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to use this code for NET.reflector using Reflexil. I am trying to replace code with this:
if(Input.GetKeyDown(KeyCode.Keypad5)) {
int i = 0;
Character localPlayer = PlayerClient.GetLocalPlayer().controllable.GetComponent<Character>();
foreach (UnityEngine.Object obj2 in UnityEngine.Object.FindObjectsOfType(typeof(LootableObject)))
{
if (obj2 != null)
{
i++;
LootableObject loot = (LootableObject) obj2;
Debug.Log("Loot "+i+": "+loot.transform.position.ToString());
CCMotor ccmotor = localPlayer.ccmotor;
if(ccmotor != null && tpPos1 != Vector3.zero) {
ccmotor.Teleport(loot.transform.position);
Notice.Popup("", "Teleported to "+loot.name, 1.5f);
}
break;
}
}
}
But it gives me an error when I try to compile:
Line: 1 Column: 1 Error Number: CS0116 Error Message: "A namespace does not directly contain members such as fields or methods"
This is Unity code I think. I am not that experienced. Could anyone fix this for me? Or tell me what to do? Thanks!
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Common Code Convention for not equal in conditional statements [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've been coming across not equal != or !condition in conditional statements ever since I started programming. Maybe it's because my brain is pre-conditioned in the English language to overthink multiple negation. But I have been wondering, is there a common development community accepted practice when it comes to evaluating for true in conditional statements? Or rather, the way I see it sometimes: evaluating for not false.
Maybe there are exceptions where != cannot be completely unavoidable?
For Example:
This might be a very simple and trivial, but is this preferred
string myStringVar = "dogs";
if (myStringVar != "dogs") //In my mind, "False this is not true"
{
//code
}
else if (myStringVar != cats) //In my mind, "True this is false"
{
//code
}
Or is this preferable
if (myStringVar == "dogs")
{
//"True"
}
else if (myStringVar == "cats")
{
//"False"
}
Then there's
bool MyBoolMethod()
{
return false;
}
if (!MyBoolMethod()) // True this method does not return true
{
//code
}
This is a very trivial and simplified example, I just want to know how to write readable, maintainable code. Does anyone else have a somewhat difficult time reading conditionals like this or is it just me?
"None of the above."
Since you're using strings, the assumption is that myStringVar can be anything. If I say:
string myStringVar = "Aardvark";
Then your first example, it will run the myStringVar != "dogs" section of code; In the second example, neither will be executed. So they're not equivalent pieces of code.
The only way they would be equivalent is if you were using Enums (in which case I would suggest using a case statement).
In your third example, it would depend on what MyBoolMethod() was named, and how easy it was to understand by a future coder. To use an example,
bool isDog()
{
return false;
}
is is easy to understand. The question then becomes is
if(!isDog()) ...
more clear than
if(isNotDog()) ...
I would argue that the first is more clear than the second. There are other situations, however, where that is not the case.
Equality and inequality are just something one needs to get comfortable with and choose in context. If the logical problem requires looking to test against equality use equality if it is looking to disqualify use inequality.
The readability and maintainability can be reinforced through good design as you started to allude to with your mybool method.
Exmaple
public class Animal
{
public static Enum AnimalType
{
Dog,
Cat
}
private _animalType;
public Animal(Enum AnimalType type)
{
AnimalType = _animalType;
}
public bool isOfType(Enum AnimalType type)
{
return _animalType == type ? true : false;
}
}
public someothermethod()
{
//doing inclusion
If(MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type matches
}
//Doing exclusion
If(!MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type does not match
}
}
You still have to get used to inequality but you know it is checking for isOfType and the named type.

Code unreachable when comparing types [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Question: My else-statement is unreachable, what am i doing wrong?
very VERY new at programming and i'm trying to compare the type so for example people can't enter strings when i'm asking for integers.
My code is probably pretty bad, if i could get a header what to do and why the if-argument skips the else-part i'd be really happy!
Thanks!
class Program
{
static void Main(string[] args)
{
int integer = 0;
start:
Console.WriteLine("How old are you?: ");
int svar = int.Parse(Console.ReadLine());
Utility.CompareTypes(svar, integer);
if (true)
{
Console.WriteLine("Thanks");
}
else
{
Console.WriteLine("You have to enter a number!");
goto start;
}
}
}
class Utility
{
public static bool CompareTypes<T01, T02>(T01 type01, T02 type02)
{
return typeof(T01).Equals (typeof(T02));
}
}
:c
It's not really a question of code, but of logic...
if (true) // <--- this will ALWAYS be true
{
Console.WriteLine("Thanks");
}
else // <--- therefore this will NEVER happen
{
Console.WriteLine("You have to enter a number!");
goto start;
}
Since your else block can never possibly execute under any logical circumstance, the entire block of code can be simplified to:
Console.WriteLine("Thanks");
In order for the else block to execute, the condition checked in the if statement needs to be false. You're currently not checking any actual condition, just a hard-coded true value.
Perhaps you meant to use the result of the previous line of code? Something like this:
var typesAreSame = Utility.CompareTypes(svar, integer);
if (typesAreSame)
{
//...

Unity error CS0029: Cannot implicitly convert type `bool' to `int' but it's bool [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have error
CS0029: Cannot implicitly convert type bool to int.
My declaration:
public bool isBig = false;
If statement with error:
if (player.GetHP() < 6 && player.isBig == false)
I don't understand this. I have also change this bool to return and checked few solutions:
player.GetBig() == false/0 / (player.GetBig()) == false/0 / !(player.GetBig())
but nothing works...
// Edit
public int GetBig()
{ // isBig is bool
return this.isBig;
}
public int GetHP()
{ // HP is int
return this.HP;
}
Simple typo.
public int GetBig()
should be
public bool GetBig()

Categories