Creating a method for multiple field validations [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
As question states I am trying to create a way to validate every field on my form. Every field on my form requires the same validation. I thought about creating a method to call to avoid re-writing code. Also for my method not to fail when it is called multiple times. How can I use the valdiations below to create a method or other type of statement for all my field validations?
if (string.IsNullOrEmpty(firstnameTextBox.Text))
{
MessageBox.Show("Please enter a first name");
}
else if (!Int32.TryParse(firstnameTextBox.Text, out number))
{
MessageBox.Show("No numbers allowed for their first name");
}
Possible method
private bool formValidation(string text)
{
int number;
if (string.IsNullOrEmpty(text))
{
MessageBox.Show("Please enter a first name");
}
else if (!Int32.TryParse(text , out number))
{
MessageBox.Show("No numbers allowed for their first name");
}
return true;
}

Problem 1: you are not returning false value when user enters empty string or invalid integer. so irrespective of the input string your method returns true always.
Solution 1: you need to return false value when user enters empty string or invalid integer.
Suggestion : String.IsNullOrEmpty() method only check wether string is null or empty but it doesnot check for whitespaces, here in your code user can enter whitespaces (user inputs from textboxes) which needs to be identified. so i would suggest you to use String.IsNullOrWhiteSpace() instead of String.IsNullOrEmpty() which will check for Null,Empty and whitespace.
Complete Code:
private bool formValidation(string text)
{
int number;
if (string.IsNullOrWhiteSpace(text))
{
MessageBox.Show("Please enter a first name");
return false;
}
else if (!Int32.TryParse(text , out number))
{
MessageBox.Show("No numbers allowed for their first name");
return false;
}
return true;
}

In situations like these, there are two better options so as not to tarnish your code with cross-cutting concerns. I tend to use Attributes that decorate fields / properties or methods in my classes and then have a general inspector read these at runtime.
Another option, similar but probably more robust, is to consider using some Aspect Oriented Programming tool such as PostSharp

Related

cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when trying to use `TryParse` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm currently learning C# and I'm having troubles. I'm getting cannot convert from 'double' to 'System.ReadOnlySpan<char>' error when I try to use !double.TryParse
static double userDouble, correctDouble;
static void someMethod() {
Console.Write(someStringOfDoubles);
while(!double.TryParse(userDouble, out _)) {
try {
userDouble= Double.Parse(Console.ReadLine());
}
catch {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
}
// checks if the userDouble is correct or not.
if (Math.Round(correctDouble, 2) == userDouble) {
Console.WriteLine("You are Correct!\n");
}
else {
Console.WriteLine("You are Incorrect.");
}
}
What should it do: Check if userDouble is a valid double and not letter(s)/word(s).
I also tried:
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}
but this gives me No overload for method 'TryParse' takes 1 arguments
Any help would be much appreciated!
You need to get console value in string variable first then check it with double.TryParse(...). Try like below.
string s = Console.ReadLine();
while(!double.TryParse(s, out userDouble)) {
Console.WriteLine($"{s} is an invalid input\n\n");
s = Console.ReadLine();
}
Below attempt of yours must work without any error. But only problem you will face is it will write 0 is an invalid input for evert input because double.TryParse will set userDouble = 0 when value from Console.ReadLine() are not double.
while(!double.TryParse(Console.ReadLine(), out userDouble)) {
Console.WriteLine($"{Convert.ToString(userDouble)} is an invalid input\n\n");
}

Best way for user to control integer [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 2 years ago.
The community is reviewing whether to reopen this question as of 2 years ago.
Improve this question
I cooked this up and was wondering if there is a better way to do this.
```Console.WriteLine("Name me.");
String cn = Console.ReadLine();
Console.WriteLine($"I like this name ,{cn}, What is my funcion? ");
String fn = Console.ReadLine();
Console.WriteLine($"I will learn how to do {fn} for you.");
Console.WriteLine("I Will double any number you give me.");
int a = Convert.ToInt32(Console.ReadLine());
int b = 2;
Console.WriteLine(a * b);
```
"Best" is subjective, but there are a few problems with the code:
Any non-number string entered will throw an exception
Any decimal number string will also throw an exception.
Instead of using Convert.ToInt32, you should consider using the TryParse method instead. This method takes in a string and an out parameter that gets set to the converted value if it's successful (otherwise 0), and it returns a bool that indicates success. If we use the decimal type, we will end up with a number that has very good precision and can include decimals.
If we then create a method with a loop that uses the result of TryParse as a condition, we can loop until the user enters a correct number.
We could also allow the user to pass in a validation method, so that they can specify what the rules are for a "valid" number (i.e. if it must be greater than zero, or must be odd, etc.).
Then we might end up with something like this:
public static decimal GetDecimalFromUser(string prompt,
Func<decimal, bool> validator = null)
{
bool isValid = true;
decimal result;
do
{
if (!isValid)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid input, please try again.");
Console.ResetColor();
}
else isValid = false;
Console.Write(prompt);
} while (!decimal.TryParse(Console.ReadLine(), out result) &&
(validator == null || !validator.Invoke(result)));
return result;
}
Similarly, we can write code that prompts the user for string input. This will save us a few lines of code in our Main method, because we don't have to keep writing Console.WriteLine and Console.ReadLine:
public static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
Now we can write code where the user cannot enter invalid input! In use, the code would then look like:
string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");

CS1061: Type `string' does not contain a definition for `classChoice' and no extension method `classChoice' [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 3 years ago.
Improve this question
I am trying to return the value of the string classChoice to a separate Class so that I can return the person's selection, I am still learning C# and have tried to understand this better i read that it needs an instance to work so i created 1, either way, i have tried about 8 different ways of doing this and all keep returning errors, what am I doing wrong?
made it a void and failed, took out the argument and tried to call only the property, tried it outside the cs file in the main cs still no luck.
public class Selection
{
public string CharSel(string classChoice = "")
{
Console.WriteLine("Welcome to the world of Text Games!");
Console.WriteLine("To begin you must select a class!");
Console.WriteLine("Lucky for you there is only 1 class to choose from at this time :-) ");
Console.WriteLine("Select a Class:");
Console.WriteLine("1. Wizard");
Console.WriteLine("2. Nothing");
Console.WriteLine("3. Nothing");
Console.WriteLine("4. Nothing");
Console.WriteLine("5. Nothing");
Console.Write("Make your selection: ");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 1)
{
classChoice = "Wizard";
Console.WriteLine("Congrats on selecting {0} now onto your adventure!", classChoice);
}
return classChoice;
}
}
public class Character
{
public static string Wizard(string name)
{
Selection s = new Selection();
string classChosen = s.CharSel().classChoice;
Console.WriteLine("Test, You are a {0}", classChosen);
name = "none yet";
return name;
}
}
Console should spiit out
Test, You are a Wizard
You have a syntax error in your program on the line:
string classChosen = s.CharSel().classChoice;
It should be:
string classChosen = s.CharSel();
CharSel() is a method which returns a string containing the value selected by the user.
You returned that string at the end of the method so when you call that method it effectively is the returned string (the value contained in the classChoice variable). That is why is is giving you that error: 'CharSel()' is a string and what you have written (s.CharSel().classChoice) is attempting to find a classChoice method on the String class (or an extension method). Just remove .classChoice from the assignment to classChosen and it will work as you expect.
Another important point is that classChoice is a private variable of the CharSel() method and isn't visible outside of the method.

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.

TryParse getting annoying [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having this really annoying issue (I know this is basic stuff) but when I try use tryparse, I have to enter 2 values before it says integer, I want it to say integer after 1 try. (btw I have to use tryparse)
here is an example.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int results = 0;
Console.WriteLine("how old are you?");
int.TryParse (Console.ReadLine(), out results);
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
else
{
Console.WriteLine("not an integer");
}
Console.ReadLine();
}
}
}
Use variables for Console.ReadLine() and int.TryParse:
Console.WriteLine("how old are you?");
string input = Console.ReadLine().Trim();
bool success = int.TryParse(input, out results);
if ( success )
{
Console.WriteLine("{0} is an integer", input); // results has the correct value
}
else
{
Console.WriteLine("{0} is not an integer", input);
}
Get rid of the first redundant call to TryParse e.g.
class Program
{
static void Main(string[] args)
{
int results = 0;
Console.WriteLine("how old are you?");
//int.TryParse(Console.ReadLine(), out results); <-- remove this
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
else
{
Console.WriteLine("not an integer");
}
Console.ReadLine();
}
}
Int32.TryParse converts the string representation of a number to its 32-bit signed integer equivalent.
A return value indicates whether the conversion succeeded.
So you can always use it like this.
if (int.TryParse (Console.ReadLine(), out results))
{
Console.WriteLine("integer");
}
On top of the other answers you may wish to do the TryParse in a while loop so that users must enter a valid integer
while(!int.TryParse(ConsoleReadLine(), out results)
Console.WriteLine("not an integer");
ConsoleWriteLine("integer");
To better explain your current issue, you are asking the user to enter two integers, but you only ever care about the second one. The first one is assigned to results but then it is overriden the next time you call TryParse without ever being used

Categories