luni, 25 august 2014

C# System Interfaces

IEquatable C# Example


IEquatable<T> Interface defines Equals method for determining equality of instances.
Example

public class Car : IEquatable<Car>
{
            public int Power { getset; }
       public bool Equals(Car other)
       {
              if (other == nullreturn false;
              if(this.Power == other.Power) return true;
              return false;
       }
       public override bool Equals(Object obj)
       {
              if (obj == nullreturn false;
              Car carObj = obj as Car;
              if (carObj == nullreturn false;
              else return Equals(carObj);
       }   
}

Car c1 = new Car();
c1.Power = 100;
Car c2 = new Car();
c2.Power = 100;
if (c1.Equals(c2)) System.Windows.MessageBox.Show("Same power");

ICloneable system interface

The ICloneable interface enables you to provide a customized implementation that creates a copy of an existing object.

Definition:

public interface ICloneable
    {
        // Summary:
        //     Creates a new object that is a copy of the current instance.
        //
        // Returns:
        //     A new object that is a copy of this instance.
        object Clone();
    } 

Example:
        public class Customer : ICloneable
        {
            public string Name { getset; }
            public Address CustomerAddress { getset; }
            public object Clone()
            {
                Customer newCustomer = (Customer)this.MemberwiseClone();
                newCustomer.CustomerAddress = (Address)this.CustomerAddress.Clone();
                 return newCustomer;
            }
        }
        public class Address : ICloneable
        {
            public string StreetName { getset; }
            public int StreetNumber { getset; }
            public object Clone()
            {
                return this.MemberwiseClone();
            }
        }

        Customer c1 = new Customer();
        c1.Name = "c1";
        Address a1 = new Address();
         a1.StreetName = "Street1";
        a1.StreetNumber = 1;
        c1.CustomerAddress = a1;

        Customer custClone = (Customer)c1.Clone();
        custClone.Name = "c2";

Niciun comentariu:

Trimiteți un comentariu