I have a problem with this construction, can not find how to rewrite it properly.

private SqlParameter op <T> (T? t, string name)
        {
            SqlParameter sp = new SqlParameter();
            sp.IsNullable = true;
            sp.ParameterName = name;
            sp.Value = t.HasValue ? t.Value : Convert.DBNull;
            return sp;
        }

What exactly is wrong with it? I suspect that calling t.HasValue will not work for most datatypes. If you are using your own datatypes you may need to use some reflection (very easy in C# compared to other languages) to figure out if the datatype actually has a .HasValue property.

Try adding some sort of functionality like this (if this is actually the problem you are having):

private bool HasValueMember (object ob)
{
    return (ob is DATA_TYPE_WITH_HASVALUE_MEMBER || ob is ANOTHER_DATATYPE_WITH_HASVALUE_MEMBER)
}

Where DATA_TYPE_WITH_HASVALUE_MEMBER and ANOTHER_DATATYPE_WITH_HASVALUE_MEMBER are known datatypes that contain this property. This kind of takes away from the genric-ness of templates, but this link might help with that a bit:

http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class

Basically it will help to determine if the object type is inherited by any of the types you know to have the member HasValue.

sp.Value = !String.IsNullOrEmpty(t.HasValue) ? (object)t.Value : DBNull.Value;

Edited 5 Years Ago by Mitja Bonca: n/a

I have a problem with this construction, can not find how to rewrite it properly.

private SqlParameter op <T> (T? t, string name)
        {
            SqlParameter sp = new SqlParameter();
            sp.IsNullable = true;
            sp.ParameterName = name;
            sp.Value = t.HasValue ? t.Value : Convert.DBNull;
            return sp;
        }

It raises this error

Error The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

Key phrase: "non-nullable value type"

So T can't be a reference type (i.e., a class), and it can't be a nullable value type (e.g., int? ).

You have to limit T to be a structure:

private SqlParameter op<T>(T? t, string name)
    where T : struct
{
    // do stuff
}
This question has already been answered. Start a new discussion instead.