Donate Share

C# Command-Line Option Parsing Library

The forum address has changed, you have been automatically redirected. Please update any bookmarks to use the new URL.

Subscribe

Nullable Type support

You are viewing a single message from this topic. View all messages.

  1. 2009-01-07 12:07:53 UTC
    Hi,
    One could add nullable type support to the library by changing OptionResult.CheckType and OptionDefinition.ConvertValue functions as as shown below.

    OptionResult
    ======
    private void CheckType(object value) {
    if (value == null &&
    !(_defintion.ValueType.IsGenericType && _defintion.ValueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) &&
    typeof(ValueType).IsAssignableFrom(_defintion.ValueType)) {
    throw new InvalidValueException("Null is not supported for this type");
    }


    OptionDefinition
    =================
    public object ConvertValue(string value) {
    try {
    if (_valueType.IsGenericType && _valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) {
    if (value == null) {
    return null;
    }

    Type underlyingType = new NullableConverter(_valueType).UnderlyingType;

    if (underlyingType.IsEnum) {
    return Enum.Parse(underlyingType, value);
    }

    return Convert.ChangeType(value,new NullableConverter(_valueType).UnderlyingType);
    }

    return Convert.ChangeType(value,_valueType);
    }
    catch (Exception ex) {
    throw new InvalidValueException("Invalue value: " + value,ex);
    }
    }

    Regards,
    Fatih Boy
< Previous | 1 | Next >

Add a Reply

This forum does not allow anonymous participation.

Log in to add a reply. Not registered? Create an account to participate and receive email updates when replies are posted to this topic.