Reputation: 3
I was tasked with creating a function that receives two numbers and returns True if both are equal and returns False if not. This is what I wrote:
int x = int.Parse(Console.ReadLine());
int y = int.Parse(Console.ReadLine());
if (x == y)
{
Console.WriteLine("True");
}
if (x != y)
{
Console.WriteLine("False");
}
I was hinted that it is possible to do this with only one line of code. Couldn't figure how to and would like to see how it's possible.
Upvotes: 0
Views: 104
Reputation: 115
Suppose your using a console to try this theory. The parsing and console reading aside.
private bool NumbersEqual(int number1, int number2)
{
return number1.Equals(number2);
}
:Edit Without the method
var number1 = 1;
var number2 = 2;
var equal = number1.Equals(number2);
Or truly truly without variable declarations and 1 line
var equal = 1.Equals(2);
Upvotes: -2
Reputation: 13248
using some newer c#7 Out variables:
Console.WriteLine(
int.TryParse(Console.ReadLine(), out int first) &&
int.TryParse(Console.ReadLine(), out int second) &&
first == second ? "True" : "False");
Upvotes: 3
Reputation: 45947
Sice Console.WriteLine(true);
outputs True
you can use
Console.WriteLine(int.Parse(Console.ReadLine()) == int.Parse(Console.ReadLine()));
Upvotes: 4
Reputation: 62439
Console.WriteLine(int.Parse(Console.ReadLine()) ==
int.Parse(Console.ReadLine()) ? "True" : "False");
This will work for any custom words you need to print, just replace the corresponding strings.
Console.WriteLine(int.Parse(Console.ReadLine()) ==
int.Parse(Console.ReadLine());
Will also work if you always want to print "True" or "False" since the ToString()
of boolean
is conveniently capitalized.
Upvotes: 0