tags:

views:

32

answers:

2

Hi,

I have an IPAddress class which has one property named ip and in its setter I am validating data coming and if data is invalid it throws an error. (Its code is as the following):

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 User Class I want to compose an object of IPAddress class.

I am doing validations for properties of User in User class and validations of Ip in IPAddress class.

My question is how I will compose IPAddress object in UserClass and what will be syntax for this ?

If I again mention get and set here with IPAddress object in User class will my earlier mentioned (in IPAddress class) getter and setter work ?

+1  A: 
  1. Create 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
    }
    
  2. Use regular expressions for IPAddress validation

Hun1Ahpu
Hi,thanks for guding. But is there no way that I may able to use validation of IPAddress class that I coded in setter ?I want to do validation using setter because it is more flexible and automatically fires. For constructer I will have to redo this if I made more than one constructors.Please guide me on this.
haansi
Any place you will change IPAddress value in your UserClass your validation will be called automatically. Or I missed your point?
Hun1Ahpu
Hun1Ahpu thanks for guiding,Please guide me on 1 thing on which I am confuse. 1st I did validations in setter of IPAddress class. In User class where I am implementing IPAddress object will I have to again worte get and set like:public IPAddress myIP { get; set; }Is it nacessary to mention 2 get and sets one in IPAddress class and 2nd in User class ?thanks
haansi
@haansi - no you should n't implement validation twice.
Hun1Ahpu
+1  A: 

Wouldn't IPAddress.TryParse help here?

shahkalpesh
shahkalpesh IPAddress is custom class and not have TryParse menthod ? can u plz explain how you suggested ?
haansi
@haansi: I wrote about the existing class named `IPAddress` in .net framework, which can serve your purpose. You could use that class instead of creating your own.
shahkalpesh