Faizan Naeem Faizan Naeem - 1 year ago 29
C# Question

how do validate the data

I have a class called

UserInfo
in which there are two properties Name and ID.

class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}


and also i have one custom exception class called
UserAlreadyLoggedInException
which called in my main method when someone try to use the Name which is already taken by someone.

class UserAlreadyLoggedInException : Exception //
{
public UserAlreadyLoggedInException() : base()
{

}
public UserAlreadyLoggedInException(string message) : base(message)
{

}
public UserAlreadyLoggedInException(string message,Exception innerException) : base(message,innerException)
{

}


Here It Is my
main
method.

try
{
UserInfo[] Ui = new UserInfo[3];
Ui[0] = new UserInfo();
Ui[1] = new UserInfo();
Ui[2] = new UserInfo();
for (int i = 0; i < 3; i++)
{
Ui[i].Id = i;
Console.WriteLine("Please inter the name of " + (i+1) + " user");
if (i == 0)
{
Ui[i].Name = Console.ReadLine();
}
else
{
Ui[i].Name = Console.ReadLine();
if (Ui[i].Name.Equals(Ui[i - 1].Name))
{
throw new UserAlreadyLoggedInException("UserName Has already taken");
}
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.GetType().Name + ex.Message);
Console.ReadLine();
}


There are 3 objects of
UserInfo
Class when [0] index object called it directly take input without any logic because it is the first object.
when [1] index called it will go in to else statement because i here is = 1 , so it will take input and compare it with (i-1) which is zero index , if the name is present it will throw an exception.if the name does not match the loop will continue and the i will become 2 this time , and now again it will go towards else statement and take input , but the prob is here .... now it will compare it with (i - 1 ) which is now become [1] index .. so it will compare the name of 2nd index with 1st index , but not with 0 index ....
how can i compare it with all of the indexes ???

Answer Source

You could put your

if (Ui[i].Name.Equals(Ui[i - 1].Name)){
    throw ...
}

code into a loop that goes from 0 -> (i - 1).

So you'd have

for (int j = 0; j < i; j++) {
    // (if logic from above, but j instead of (i - 1))
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download