Monday, 20 February 2012

What is Interface based Polymorphism?


Yes, we can see interface based polymorphim with the help one interface is called IFormatable.


 public interface IFormattable
{

    string ToString(string format, IFormatProvider formatProvider);
}

 yes, IFormatable has only one method.but when we Formatting the data.Which will shows different Signatures to Same ToString() method.

Ex:

what are these 4 constructors of int.ToString() type?
but Integer inherities the IFormatable and IFormatable contains only one method but what about ramaining 3 constructors of  ToString() methods.
yes Int datatype maintains the polymorphism with different signatures of  ToString() like below

public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
{
     public override string ToString();
     public string ToString(IFormatProvider provider);
     public string ToString(string format);
                                                // Above 3 are polymorphism based methods.
     public string ToString(string format, IFormatProvider provider);
}

so like that every type having different signatures of their own implementation.

Example of Datatime with Four types of Implementation.

System.Globalization;

           CultureInfo culinfo = new CultureInfo("es-ES");
            DateTime dt = new DateTime();
            dt = DateTime.Now;
            Console.WriteLine(dt);
            Console.WriteLine(dt.ToString());
            Console.WriteLine(dt.ToString(culinfo));
            Console.WriteLine(dt.ToString("mm-dd-yy", culinfo));
            Console.WriteLine(dt.ToString("dd-mm-yy"));
            Console.WriteLine(dt.ToString("yy-dd-mm"));
            Console.ReadKey();

this is called Interface based Polymorphism.

No comments:

Post a Comment