Convert T To String - CSharp System.Xml

CSharp examples for System.Xml:XML String

Description

Convert T To String

Demo Code


using System.Text;
using System.Reflection;
using System.Xml;
using System.Collections.Generic;
using System.Collections;
using System.Net;
using System.Drawing;
using System;//from www .j  ava  2 s . c o m

public class Main{
        /// <summary>
      /// 
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="value"></param>
      /// <returns></returns>
      public static string ToString<T>(T value)
      {
         object valueObject = value;

         Type type = value.GetType();
         string stringValue;

         if (type.IsEnum)
         {
            stringValue = valueObject.ToString();
         }
         else
         {
            switch (type.Name)
            {
               case "Point":
                  {
                     Point point = (Point)valueObject;
                     stringValue = string.Format("{0}, {1}", point.X, point.Y);
                     break;
                  }

               case "Color":
                  {
                     Color color = (Color)valueObject;
                     stringValue = string.Format("{0}, {1}, {2}, {3}", color.R, color.G, color.B, color.A);
                     break;
                  }

               case "Rectangle":
                  {
                     Rectangle rectangle = (Rectangle)valueObject;
                     stringValue = string.Format("{0}, {1}, {2}, {3}", rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
                     break;
                  }

               case "DateTime":
                  {
                     DateTime dateTime = (DateTime)valueObject;
#if WINDOWS
                     stringValue = dateTime.ToBinary().ToString();
#else
                     stringValue = dateTime.Ticks.ToString();
#endif
                     break;
                  }

               case "TimeSpan":
                  {
                     TimeSpan timeSpan = (TimeSpan)valueObject;
                     stringValue = timeSpan.Ticks.ToString();
                     break;
                  }

               default:
                  stringValue = valueObject.ToString();
                  break;
            }
         }

         return stringValue;
      }
}

Related Tutorials