Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast string.Empty to (generic) T in C#?

I have a utility method which returns a strongly typed value from an old .INI configuration type file, with the signature

internal static T GetIniSetting<T>(string config, string key, T defVal = default(T))

I want strings to be special, in that I would like the default value for defaultValue to be string.Empty, not default(string) (i.e. null), in the case when the coder hasn't specified a default value.

if (cantFindValueInIniFile == true)
{
    if ((typeof(T) == typeof(string)) && (defaultValue == null))
    {
        // *** Code needed here - Cannot convert string to <T>***
        return (T)string.Empty; 
    }
    return defaultValue;
}

I've tried hard casting, and the as keyword, to no avail.

like image 465
StuartLC Avatar asked Jun 08 '12 04:06

StuartLC


2 Answers

The 'hacky' way:

return (T)(object)string.Empty; 

Notes:

  • Pretty safe as you have check pre-conditions.
  • Performance penalty unnoticeable on reference types.
like image 158
leppie Avatar answered Nov 10 '22 09:11

leppie


You have to do it like this: (T)(object)(string.Empty).

Also, a minor optimization is to store this in a static readonly string field so that you don't have to do the casts but one time per generic parameter (instead of per method call)

like image 7
smartcaveman Avatar answered Nov 10 '22 10:11

smartcaveman