Why not just overload the methods?
using System;
namespace test {
static class Formatter {
const string DateFormat = "MMM dd yyyy";
const string NumberFormat = "0.0";
public static string Format(double d) {
return d.ToString(NumberFormat);
}
public static string Format(DateTime d) {
return d.ToString(DateFormat);
}
public static string Format(object o) {
return o.ToString();
}
}
class Program {
public static void Main() {
Console.WriteLine(Formatter.Format(2.0d));
Console.WriteLine(Formatter.Format(DateTime.Now));
Console.WriteLine(Formatter.Format(4));
}
}
}
NOTE : if you need to compare types, you should use
if (typeof(int) == t){
}
and not make comparisons of the type name (or at least if you do), check the names completely , i.e. including namespace).
EDIT
An alternative solution that takes Allon's comment into account using a dictionary type function:
using System;
using System.Collections.Generic;
namespace test {
public class Formatter {
delegate string FormatFunction(object o);
private string FormatDouble(object o) {
double d = (double)o;
return d.ToString("0.0");
}
private string FormatDateTime(object o) {
DateTime d = (DateTime)o;
return d.ToString("MMM dd yyyy");
}
private Dictionary<Type, FormatFunction> _formatters = new Dictionary<Type, FormatFunction>();
public Formatter() {
_formatters.Add(typeof(double), FormatDouble);
_formatters.Add(typeof(DateTime), FormatDateTime);
}
public string Format(object o) {
Type t = o.GetType();
if (_formatters.ContainsKey(t)){
return _formatters[t](o);
} else {
return o.ToString();
}
}
}
class Program {
public static void Main() {
Formatter f = new Formatter();
Console.WriteLine(f.Format(2.0d));
Console.WriteLine(f.Format(DateTime.Now));
Console.WriteLine(f.Format(4));
}
}
}
, ( - , ).