2003-07-02 Andreas Nahr <ClassDevelopment@A-SoftTech.com>
[mono.git] / mcs / class / System / System.ComponentModel / BaseNumberConverter.cs
1 //
2 // System.ComponentModel.BaseNumberConverter.cs
3 //
4 // Authors:
5 //   Andreas Nahr (ClassDevelopment@A-SoftTech.com)
6 //
7 // (C) 2002/2003 Ximian, Inc (http://www.ximian.com)
8 // (C) 2003 Andreas Nahr
9 //
10
11 using System;
12 using System.Globalization;
13
14 namespace System.ComponentModel
15 {
16         public abstract class BaseNumberConverter : TypeConverter
17         {
18
19                 internal Type InnerType;
20
21                 protected BaseNumberConverter()
22                 {
23                 }
24
25                 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
26                 {
27                         if (sourceType == typeof (string)) 
28                         return true;
29                         return base.CanConvertFrom (context, sourceType);
30                 }
31
32                 public override bool CanConvertTo(ITypeDescriptorContext context, Type t)
33                 {
34                         if (t == typeof (string))
35                                 return true;
36
37                         return base.CanConvertTo (context, t);
38                 }
39
40                 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
41                 {
42                         if (value.GetType() == typeof (string)) {
43                                 try {
44                                         return Convert.ChangeType (value, InnerType, culture.NumberFormat);
45                                 } catch (Exception e) {
46                                         // LAMESPEC MS just seems to pass the internal Exception on to the user
47                                         // so it throws a pure Exception here. We should probably throw a 
48                                         // ArgumentException or something like that
49                                         throw e;
50                                 }
51                         }
52
53                         return base.ConvertFrom (context, culture, value);
54                 }
55
56                 public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
57                                                  object value, Type destinationType)
58                 {
59                         if (value == null)
60                                 throw new ArgumentNullException ("value");
61
62                         if (destinationType == typeof (string) && value.GetType() == InnerType)
63                                 return Convert.ChangeType (value, typeof (string), culture.NumberFormat);
64
65                         return base.ConvertTo (context, culture, value, destinationType);
66                 }
67         }
68 }
69