Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Conversion from .net types to obj-c types

$
0
0

Hi all,

I'm writing a helper class which will wrap a native iOS library in Xamarin. One of the native properties I want to reference is of type NSObject, and I would like to get automatic conversion from sensible .net types to objc types where available - i.e. double, int, short etc to NSNumber, DateTime to NSDate etc.

I know that mono will perform the conversion for you if the native type is specified (i.e. the property is of NSNumber type), however as I mentioned the properties I have are of type NSObject.

Am I missing an easy way to do this? At the moment I've written the following extension method on System.Object, which will attempt to convert the types I care about:

public static class NSObjectConversionExtensions
{
    /// <summary>
    /// Attempts to convert native .net types to objC types.
    /// Works for:
    ///  - DateTime
    ///  - String
    ///  - Number types
    /// </summary>
    /// <returns>The objective C representation</returns>
    /// <param name="o">The .net object</param>
    public static NSObject ConvertToNSObject(this object o)
    {
        NSObject toReturn;
        // Specific types first - DateTime
        if (o is DateTime) {
            toReturn = (NSDate)((DateTime)o);
        }
        // Now a String
        else if (o is string) {
            toReturn = (NSString)((string)o);
        }
        // And a catch-all for number types
        else if (typeof(IConvertible).IsAssignableFrom (o.GetType ())) {
            try {
                // Most types will convert happily to a double
                toReturn = (NSNumber)(((IConvertible)o).ToDouble (CultureInfo.InvariantCulture.NumberFormat));
            } catch (InvalidCastException e) {
                throw new InvalidCastException ("Unable to convert from .net type to objC type.", e);
            }
        }
        // We can't do it
        else {
            throw new InvalidCastException ("Unable to convert from .net type to objC type.");
        }

        // Send the result back
        return toReturn;
    }
}

Does anybody have any better suggestions? If not, has anybody else faced this problem? What did you do to solve it?

Much appreciated

sam


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>