Using a ComboBox as filter - c#

I have made a program that is a kind of a wiki, but in a program. I've added lots of pictureBoxes, and I have 3 filters to sort those pictureBoxes: ROLE, ATTACK TYPE and NAME.
What I'd like to do is, like, if you select the Attack Type RANGED it disables the other pictureBoxes that has a different Attack Type than RANGED.
I've tried comparing each Hero (I've made a different class for it) with a timer, but I didn't know how to do it.
I also tried this
if(comboBox1.Text == "RANGED") { //do stuff }
But I don't know how could I access all of the heroes inside an array I made, and check if they have atkType = RANGED.
My Hero.cs class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace WindowsFormsApplication1
{
public struct Hero
{
public string Name;
public string Role; /* carry, disabler, lane support, initiator, jungler, support, durable, nuker, pusher, escape */
public string atkType; /* melee or ranged */
public string Type; /* strength, agility or intelligence */
public string imgName;
public Hero(string name, string role, string atktype, string type, string imgname)
{
Name = name;
Role = role;
atkType = atktype;
Type = type;
imgName = imgname;
}
public static Hero[] heroes = new Hero[] {
new Hero() {Name = "test", Role = "", atkType = "Melee", Type = "Strength", imgName = "test" }
};
}
}
I've managed to get the filter working, but now, there's only a problem: I can't dispose (images wont unload) the current loaded images and can't load new ones.
What I tried:
if (melee == false && ranged == false)
{
for (int i = 0; i < Hero.heroes.Length; i++)
{
imgs[i].Load("http://cdn.dota2.com/apps/dota2/images/heroes/" + Hero.heroes[i].imgName + "_sb.png");
comboBox3.Items.Add(Hero.heroes[i].Name);
//imgs[i].MouseHover += displayInfo(i);
}
}
if (ranged == true)
{
for (int i = 0; i < Hero.heroes.Length && Hero.heroes[i].atkType.Contains("Ranged"); i++)
{
imgs[i].Image.Dispose();
imgs[i].Load("http://cdn.dota2.com/apps/dota2/images/heroes/" + Hero.heroes[i].imgName + "_sb.png");
}
}

The code could be something like this:
if(cmb.text=="goofy")
//Code
else if(cmb.text=="mars")
//Other code
else
//BLA BLA

Related

StackOverFlow Exception while creating objects in C#

I am trying to display the details of the movie but I am getting StackOverFlow exception in cast class where I am returning actorNames array.
I am trying to make the movie object. In movie object, I am creating objects for Cast and Genre class and passing them in movie class constructor with the data.
Kindly let me know how I can correct this issue. This issue might exist for Genre class as well. Please let me know if there is any case like that as well.
// Genre Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Genre
{
private static Dictionary<string, string> genre = new Dictionary<string, string>();
public string[] genreName { get { return genreName; } set { } }
public string[] genreDescription { get { return genreDescription; } }
public Genre() {
setGlobalGenreDictionary();
}
public Genre(string[] nameOfGenre) {
this.genreName = nameOfGenre;
setGenreDecsription(nameOfGenre);
}
public void setGenreDecsription(string[] genreName) {
int i = 0;
foreach(KeyValuePair<string, string> gen in genre) {
if (gen.Key == genreName[i]) {
genreDescription[i] = gen.Value;
}
i++;
}
}
public void setGlobalGenreDictionary() {
genre.Add("Action", "Associated with particular types of spectacle (e.g., explosions, chases, combat)");
genre.Add("Adventure", "Implies a narrative that is defined by a journey (often including some form of pursuit) and is usually located within a fantasy or exoticized setting. Typically, though not always, such stories include the quest narrative. The predominant emphasis on violence and fighting in action films is the typical difference between the two genres.");
genre.Add("Animation", "A film medium in which the film's images are primarily created by computer or hand and the characters are voiced by actors. Animation can otherwise incorporate any genre and subgenre and is often confused as a genre itself");
genre.Add("Comedy", "Defined by events that are primarily intended to make the audience laugh");
genre.Add("Drama", "Focused on emotions and defined by conflict, often looking to reality rather than sensationalism.");
genre.Add("Fantasy", "Films defined by situations that transcend natural laws and/or by settings inside a fictional universe, with narratives that are often inspired by or involve human myths. The genre typically incorporates non-scientific concepts such as magic, mythical creatures, and supernatural elements.");
genre.Add("History", "Films that either provide more-or-less accurate representations of historical accounts or depict fictional narratives placed inside an accurate depiction of a historical setting.");
genre.Add("Horror", "Films that seek to elicit fear or disgust in the audience for entertainment purposes.");
genre.Add("Noir", "A genre of stylish crime dramas particularly popular during the 1940s and '50s. They were often reflective of the American society and culture at the time.");
genre.Add("Science Fiction", "Films are defined by a combination of imaginative speculation and a scientific or technological premise, making use of the changes and trajectory of technology and science. This genre often incorporates space, biology, energy, time, and any other observable science.");
genre.Add("Thriller", "Films that evoke excitement and suspense in the audience. The suspense element found in most films' plots is particularly exploited by the filmmaker in this genre. Tension is created by delaying what the audience sees as inevitable, and is built through situations that are menacing or where escape seems impossible.");
genre.Add("Western", "A genre in which films are set in the American West during the 19th century and embodies the \"spirit, the struggle and the demise of the new frontier.\" These films will often feature horse riding, violent and non-violent interaction with Native-American tribes, gunfights, and technology created during the industrial revolution.");
}
}
}
//Movie Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Movie
{
int movieId;
string movieTitle;
string storyline;
double rating;
int year;
Cast cast;
Genre genre;
public Movie(int id, string title, string story, double rating, int yr, Cast castObj, Genre genObj) {
movieId = id;
movieTitle = title;
storyline = story;
this.rating = rating;
year = yr;
this.cast = castObj;
this.genre = genObj;
}
public void getMovie() {
Console.WriteLine("Movie:" + this.movieTitle + "\n"
+ "Year:" + this.year + "\n"
+ "IMDB Rating:" + this.rating + "/10\n "
+ "Storyline:" + this.storyline );
Console.WriteLine("Cast:");
try
{
int noOfMembers = this.cast.actorNames.Length;
for (int i = 0; i < noOfMembers; i++)
{
Console.WriteLine(cast.roles + ":" + cast.actorNames);
}
}
catch (Exception e)
{
Console.WriteLine(e.GetType());
}
int noOfGenres = this.genre.genreName.Length;
for (int i = 0; i < noOfGenres; i++)
{
Console.WriteLine(this.genre.genreName + ":" + this.genre.genreDescription);
}
}
}
}
//Cast Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Cast
{
public string[] actorNames {
get
{
return actorNames;
}
set { } }
public string[] roles { get { return roles; } set { } }
int referenceToMovie;
public Cast(string[] actorNames, string[] roles, int reference) {
this.actorNames = actorNames;
this.roles = roles;
this.referenceToMovie = reference;
}
}
}
//Main Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
class Program
{
static void Main(string[] args)
{
string castNames = "Kenneth Branagh,Patrick Doyle,Chris Hemsworth,Natalie Portman";
string castRoles = "Director,Music,Actor,Actor";
string genresOfTheMovie = "Action,Adventure,Fantasy";
Movie thor = new Movie(0800369, "Thor", "The powerful but arrogant god Thor is cast out of Asgard to live amongst humans in Midgard (Earth), " +
"where he soon becomes one of their finest defenders.", 7.0, 2011, new Cast(castNames.Split(','), castRoles.Split(','), 0800369), new Genre(genresOfTheMovie.Split(',')));
thor.getMovie();
//Movie ironman = new Movie();
//Movie hulk = new Movie();
//Movie avengers = new Movie();
//Movie blackPanther = new Movie();
}
}
}
There are many issues with your code:
Genre:
you set a global genre Dictionary on every initialization of Genre. This means you'll be adding all of the items every time Genre you try to create a Genre.
private static Dictionary<string, string> genre = new Dictionary<string, string>();
//make this static
public static void SetGlobalGenreDictionary()
and then call it
Genre.SetGlobalGenreDictionary();
in your program
For your properties, they are what is causing your StackOverflow issue.
There are a couple of ways to write these, but your version will keep calling itself causing the stack overflow.
//Option 1:
public string[] GenreName1 { get; set; }
//Option 2:
private string[] genreName2;
public string[] GenreName2 {
get
{
return genreName2;
}
set
{
//you have to write a Set method body if you write a get method. Otherwise nothing will happen. If you don't want to set it, don't write a set method at all.
genreName2 = value;
}
}
There are other issues, but this should get you started on your homework problem.

Breadth First Search Algorithm Does Not Work Results in Infinite Loop

I am trying to do a BFS search where I dynamically create the Nodes of the graph as I search the State Space. I followed the book but it does not work the frontier keeps on running and the explored set stays at the start value only. Please help, I have been stuck here for 4 days. Still a beginner programmer.
Problem Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class Problem
{
public State start { get; set; }
public State end { get; set; }
public string[] action = { "UP", "LEFT", "DOWN", "RIGHT" };
public Problem(State x, State y)
{
start = x;
end = y;
}
public State Result(State s , string a)
{
State up;
if (a == "UP" && s.X - 1 >= 0)
{
up = new State(s.X - 1, s.Y);
}
else if (a == "LEFT" && s.Y - 1 >= 0)
{
up = new State(s.X, s.Y-1);
}
else if (a == "DOWN" && s.X + 1 < 5)
{
up = new State(s.X, s.Y+1);
}
else if( a == "RIGHT" && s.Y + 1 < 11)
{
up = new State(s.X + 1, s.Y);
}
return up;
}
public bool GoalTest(Node<State> goal)
{
if (goal.Data.Equals(end))
{
return true;
}
return false;
}
}
}
Search Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class Search
{
public void BFS(Problem p)
{
Queue<Node<State>> frontier = new Queue<Node<State>>();
HashSet<string> explored = new HashSet<string>();
List<Node<State>> nNodes = new List<Node<State>>();
Node<State> root = new Node<State>() {Data = p.start,};
frontier.Enqueue(root);
while(frontier.Count > 0)
{
Node<State> next = frontier.Dequeue();
if(!explored.Add(next.Data.Data)) continue;
next.Children = new List<Node<State>>();
foreach(string action in p.action)
{
next.Children.Add(new Node<State>() { Data = p.Result(next.Data, action), Parent = next });
}
for(int i = 0; i < next.Children.Count; i++)
{
if (p.GoalTest(next.Children[i]) == true)
{
//Solution(next.Children[i]);
break;
}
frontier.Enqueue(next.Children[i]);
}
}
}
public void Solution(Node<State> n)
{
while(n.Parent != null)
{
Console.WriteLine(n.Parent.Data);
}
}
}
}
Node Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class Node<T>
{
public T Data { get; set; }
public Node<T>? Parent { get; set; }
public List<Node<T>> Children { get; set; }
}
}
State Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
internal class State
{
public int X { get; set; }
public int Y { get; set; }
public string Data { get; }
public State(int x, int y)
{
X = x;
Y = y;
Data = $"{X}-{Y}";
}
}
}
Main Program
using Test;
State start = new State(0, 1);
State end = new State(3, 7);
Problem p = new Problem(start, end);
Search s = new Search();
s.BFS(p);
This is actually for my assignment hence I named it test.
I am trying to implement the pseudocode from here: (Page 82)
https://zoo.cs.yale.edu/classes/cs470/materials/aima2010.pdf
Update
It does not stuck now but it does not input anything into the console after the loop runs it is supposed to get the links between the goal node and the start node via the "Parent property".
You are never checking if nodes are already explored, so you will likely enter an infinite loop:
explored.Add(next.Data.Data);
should be
if(!explored.Add(next.Data.Data)) continue;
But there might be other problems with the code. I would highly recommend reading Eric Lipperts article How to debug small programs since problems like this should be fairly easy to find and fix yourself with the help of a debugger. Learning how to use a debugger is an invaluable skill that will make troubleshooting much easier.
I would also recommend removing all the strings from your program. Instead you should create type representing a coordinate, i.e. a Point, or vector2Int. I would recommend making this a readonly struct, and add ToString overload, IEquality<Point> implementation, operators for addition subtraction, equality etc. This type could then be used both for representing the state, and to represent the offsets. Such a type would be reusable for all kinds of different projects.

write changes in a csv file with c#

I am trying to change a value of csv file in C# console.
First I load the content of the csv file into the code. Then I change a value and try to save it.
This is the content of the csv before (and sadly after) execution:
1;Geg;17
2;Geg;17
3;Geg;17
During runtime the values change into:
new Values
But somehow they do not get saved into the csv file.
This is my code:
main class:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
namespace csvtest
{
class Program
{
static void Main(string[] args)
{
Tabelle tab = new Tabelle();
foreach (Employees e in tab.getAll())
{
Console.WriteLine(e);
}
tab.updating(1, "fafdsdsf", 323);
}
}
}
Tabelle class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace csvtest
{
class Tabelle
{
private List<Employees>liste;
public Tabelle()
{
liste = new List<Employees>();
string[] rows = File.ReadAllLines(#"C:\Users\rbc\Desktop\csvtest\csvtest\obj\test.csv");
foreach (string row in rows)
{
string[] information = row.Split(';');
int number = int.Parse(information[0]);
string name = information[1];
double salary = double.Parse(information[2]);
liste.Add(new Employees { Number = number, Name = name, Salary = salary });
}
}
public Employees[] getAll()
{
return liste.ToArray();
}
public void adding(int number, string name, double salary)
{
liste.Add(new Employees { Number = number, Name = name, Salary = salary });
}
public void updating(int number, string name, double salary)
{
foreach (Employees e in liste)
{
if (e.Number == number)
{
e.Name = name;
e.Salary = salary;
}
}
}
~Tabelle()
{
string[] information = new string[liste.Count];
for (int i = 0; i<liste.Count; i++)
{
information[i] = liste[i].Number + ";" + liste[i].Name + ";" + liste[i].Salary;
}
File.WriteAllLines(#"C:\Users\rbc\Desktop\csvtest\csvtest\obj\test.csv", information);
}
}
}
Employees class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace csvtest
{
class Employees
{
public int Number { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
public override string ToString()
{
return Number + "|" + Name + "|" + Salary;
}
}
}
I have no idea what the problem is. I appreciate any ideas or hints.
Thanks a lot in advance for your help!!
As other people suggested here, it's true that the developer hasn't control over when the finalizer is called. The garbage collector decides when to free the memory.
But, you should look at Dispose. If you implement IDisposable, and dispose of your object, then the code in Dispose will run.
First of all, your class should implement the above interface
class Tabelle : IDisposable
Then you need to wrap your code from destructor with the Dispose() method.
public void Dispose()
{
string[] information = new string[liste.Count];
for (int i = 0; i < liste.Count; i++)
{
information[i] = liste[i].Number + ";" + liste[i].Name + ";" + liste[i].Salary;
}
File.WriteAllLines(#"data.txt", information);
GC.SuppressFinalize(this);
}
Also, don't forget to use using keyword when creating your class.
using (Tabelle tab = new Tabelle())
{
foreach (Employees e in tab.getAll())
{
Console.WriteLine(e);
}
tab.updating(1, "fafdsdsf", 323);
}

What is the difference between creating a new guid instance or selecting in Visual Studio tools > create guid?

In my state script I select Tools > Create GUID > New GUID > Copy
The script is looking like this now :
The guide is not the same as in the screenshot it's just for example.
The problem is that on each object I want to add to this state script format I need manually to generate a new GUID copy it and paste it to the code and it's a bit annoying. So I wonder what is the difference between creating a new guid instance or selecting in visual studio tools > create guide.
This is when creating a new instance :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateGuid : MonoBehaviour
{
public string uniqueGuidID;
private Guid guidID;
public void GenerateGuidNum()
{
guidID = Guid.NewGuid();
uniqueGuidID = guidID.ToString();
}
}
I wonder why not use the same new instance technic in both cases, why or what the tool for creating guide number 5 is for ?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateTest : MonoBehaviour, IStateQuery
{
private State m_state = new State();
public Guid UniqueId => Guid.Parse("571E6219-DFD4-4893-A3B0-F9A151BFABFE");
private class State
{
public bool s1;
// bool the kid holding the navi is true
}
public string GetState()
{
return JsonUtility.ToJson(m_state);
}
public void SetState(string jsonString)
{
m_state = JsonUtility.FromJson<State>(jsonString);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
I will edit and update the usage of it :
With this script :
using System;
public interface IStateQuery
{
string GetState();
void SetState(string jsonString);
Guid UniqueId { get; }
}
In the TestState script I'm using the IStateQuery :
public class StateTest : MonoBehaviour, IStateQuery
Then use it like this in the Save and Load methods :
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SaveLoad : MonoBehaviour
{
public FadeInOutSaveGameText fadeInOutSaveGame;
public float timeToStartSaving;
public float savingFadeInOutTime;
private string saveString;
private void Awake()
{
SaveSystem.Init();
}
public void Save(string Folder, string FileName)
{
var objectsToSave = UpdateObjectsToSave();
SaveGame saveGame = new SaveGame();
saveGame.saveObjects = new List<SaveObject>();
for (int i = 0; i < objectsToSave.Count; i++)
{
SaveObject saveObject = new SaveObject();
saveObject.transformSaver = new TransformSaver();
Debug.Log($"{i}");
Debug.Log($"{objectsToSave[i].name}");
saveObject.gameObjectUniqueID = objectsToSave[i].GetComponent<GenerateGuid>().uniqueGuidID;
var x = objectsToSave[i].GetComponents<Component>();
var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
List<KeyToValue> componentsState = new List<KeyToValue>();
foreach (var z in stateQueryComponent)
{
var w = z as IStateQuery;
componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
}
saveObject.transformSaver.position = objectsToSave[i].transform.position;
saveObject.transformSaver.rotation = objectsToSave[i].transform.rotation;
saveObject.transformSaver.scaling = objectsToSave[i].transform.localScale;
saveObject.componentsState = componentsState;
saveGame.saveObjects.Add(saveObject);
}
string json = JsonUtility.ToJson(saveGame);
if (Folder == null && FileName == null)
{
SaveSystem.Save(json);
}
else
{
SaveSystem.Save(Folder, FileName, json);
}
}
public void Load(string Folder, string FileName)
{
var objectsToLoad = UpdateObjectsToSave();
Dictionary<string, GameObject> uniqueIdToObject = objectsToLoad
.ToDictionary(o => o.GetComponent<GenerateGuid>().uniqueGuidID, o => o);
saveString = SaveSystem.Load(Folder, FileName);
if (saveString != null)
{
SaveGame saveGame = JsonUtility.FromJson<SaveGame>(saveString);
foreach (var saveObject in saveGame.saveObjects)
{
List<KeyToValue> loadedComponents = saveObject.componentsState;
if (uniqueIdToObject.ContainsKey(saveObject.gameObjectUniqueID))
{
var objectToSetState = uniqueIdToObject[saveObject.gameObjectUniqueID];
objectToSetState.transform.position = saveObject.transformSaver.position;
objectToSetState.transform.rotation = saveObject.transformSaver.rotation;
objectToSetState.transform.localScale = saveObject.transformSaver.scaling;
var y = objectToSetState.GetComponents<Component>();
var z = y.Where(component => component is IStateQuery).ToList();
Dictionary<string, IStateQuery> zz = z.ToDictionary(sq => (sq as IStateQuery).UniqueId.ToString(), sq => sq as IStateQuery);
foreach (KeyToValue keyvalue in loadedComponents)
{
zz[keyvalue.Key].SetState(keyvalue.Value);
}
}
}
}
}
private List<GameObject> UpdateObjectsToSave()
{
var objectsWithGenerateGuid = GameObject.FindObjectsOfType<GenerateGuid>().ToList();
var objectsToSave = new List<GameObject>();
if (objectsWithGenerateGuid.Count > 0 && objectsToSave.Count == 0)
{
for (int i = 0; i < objectsWithGenerateGuid.Count; i++)
{
objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);
}
}
return objectsToSave;
}
public IEnumerator AuatomaticSaveWithTime()
{
yield return new WaitForSeconds(timeToStartSaving);
Save(null, null);
StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
}
public IEnumerator SaveWithTime(string Folder, string FileName)
{
yield return new WaitForSeconds(timeToStartSaving);
Save(Folder, FileName);
StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
}
}
Depends on what you want, really.
The Visual Studio tool is meant to generate guid you are free to use for whatever you like. It isn't tied to your code in any way. You can of course use these values as static resources for your app, so they will always be the same at runtime.
The Guid.NewGuid will generate a new Guid value whenever your code runs. It will always be dynamic, even for the same object. You run the same app today and tomorrow, you'll get different guids.
Based on your comments, my understanding is that you really are looking for an easier way to inject static guids in your code editor to uniquely identify component types. If that's the case, have a look at the following extension:
https://marketplace.visualstudio.com/items?itemName=florians.InsertGUIDCommand
It will allow you to use SHIFT-ALT-G to inject a brand new guid value in your code. It should save you a few mouse clicks. ;)

Multi-level validation for an Object in C#

I have a Console project reads inputs from CSV file and tries to save them to database.
For that, I created a class Person that maps a CSV row.
The CSV file has two columns Name and Age. Person class is like.
class Person
{
public string Name;
public int Age;
}
So the list of all populated objects is List<Person>.
I have a new requirement to display validation messages to console before proceed with saving populated objects to database.
Validation has two levels: Error and Warning.
For example if Name property contains a special character, I have to display this message: "Error: Name contains special character"
In case Name properly contains a numeric character, I have to display only warning message: "Warning: Name contains numeric character"
I was thinking about using DataAnnotation but I cannot see a way to add different levels (Error and Warning) to validation process. Also, I'm not sure if DataAnnotation fits only in Web Applications.
Is there a way to add some functionality to Person class to get this validation done for each property?
NB: This is just an example to better understand the question, I have other rules for other properties.
You could change the Name field to a property, and incorporate this error checking into its setter. For checking if the string contains special characters though, you will need to build an array of characters you want to look for and see if any of those match a character within the string.
An example can be found here.. Special Character Check
class Person
{
private static readonly char[] numbers = "0123456789".ToCharArray();
private static readonly char[] specialChars = "!##$%^&*()".ToCharArray();
private string _name;
public string Name
{
set
{
if (Validate(value, "Name"))
_name = value;
}
get { return _name; }
}
public int age;
private bool Validate(string input, string varName)
{
bool isValid = true;
if (input.IndexOfAny(specialChars) != -1)
{
Console.WriteLine("Error- " + varName + " contains a special character.");
isValid = false;
}
if (input.IndexOfAny(numbers) != -1)
Console.WriteLine("Warning- " + varName + " contains a number.");
//optionally set isValid = false if warnings warrant this
return isValid;
}
}
Any other strings your person class contains can be formatted with properties in this same way.
add a public "validation" function inside Person - you will be able to call that function from outside the class
Use Regex class to search for digits.
define your own special characters inside an array and use Contains() method to check if the name contains special chars.
return aftermath using enum (one way to do that) and handle names that are not valid
here is a general idea for what you need (please see comments):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Foo();
}
private static void Foo()
{
// init new object
Person p1 = new Person { age = 55, Name = "jonat8han" };
Person p2 = new Person { age = 55, Name = "jonat#han" };
Person p3 = new Person { age = 55, Name = "jonathan" };
List<Person> p = new List<Person>();
p.Add(p1);
p.Add(p2);
p.Add(p3);
foreach (Person person in p)
{
if (person.IsValid() == Person.Validation.IsWarning)
{
Console.WriteLine(person.Name + " has digit...");
Console.ReadLine();
// write here some logic to do somthing with this....
}
else if (person.IsValid() == Person.Validation.IsError)
{
Console.WriteLine(person.Name + " special char...");
Console.ReadLine();
// write here some logic to do somthing with this....
}
else if (person.IsValid() == Person.Validation.IsErrorAndWarning)
{
Console.WriteLine(person.Name + " special char and digit...");
Console.ReadLine();
// write here some logic to do somthing with this....
}
else
{
// everything IsOk
}
}
}
class Person
{
public enum Validation
{
IsWarning = 0,
IsError = 1,
IsErrorAndWarning = 2,
IsOk = 3
}
public string Name;
public int age;
public Validation IsValid()
{
if (IsError() && IsWarning())
{
return Validation.IsErrorAndWarning;
}
else if (IsError())
{
return Validation.IsError;
}
else if (IsWarning())
{
return Validation.IsWarning;
}
else
{
return Validation.IsOk;
}
}
private bool IsWarning()
{
// check if there are digits...
Regex reg = new Regex("\\d");
if (reg.IsMatch(this.Name) == true)
{
// there is digit
return true;
}
else
{
return false;
}
}
private bool IsError()
{
string[] speacialChars = new string[] { "*", "&", ".", "^", "#", "#" }; // define here what is a special character for your needs
foreach (Char c in this.Name)
{
if (speacialChars.Contains(c.ToString()))
{
return true;
}
}
return false;
}
}
}
}

Categories

Resources