How to do checks when composing a class object in another class?
I have a class IPAddress that has one property named ip and in its setter. I check the data and if the data is not valid it throws an error. (His code looks like this:
private string ip;
public string IP
{
get { return ip; }
set { string PartsOfIP = value.Split('.');
if (PartsOfIP.Length == 4)
{
foreach (string part in PartsOfIP)
{ int a = 0; bool result = int.TryParse(part, out a);
if (result != true)
{
throw new Exception("Invalid IP");
}
else { ip = value; }
}
}
else { throw new Exception("Invalid IP");
}
}
In the user class I want to create an object of the IPAddress class.
I am performing property checks on User in User class and Ip checks on IPAddress class.
My question is how will I link the IPAddress object in the UserClass and what is the syntax for that?
If I mentioned get again and set an IPAddress object here in the User class, would my previously mentioned (in the IPAddress class) work with getter and setter?
+2
a source to share
2 answers
-
Create a constructor for UserClass like this:
public IPAddress userIpAddress; // Other fields and properties public UserCLass(IPAddress ipAddress, .... other fields) { userIpAddress = ipAddress; // here validation for IPAddress will be called }
-
Use Regular Expressions to Check IPAddress
+1
a source to share