Is it possible to write similar construction?
I want to set, somehow, default value for argument of type T.
private T GetNumericVal<T>(string sColName, T defVal = 0)
{
string sVal = GetStrVal(sColName);
T nRes;
if (!T.TryParse(sVal, out nRes))
return defVal;
return nRes;
}
Additionally, I found following link:
Generic type conversion FROM string
I think, this code must work
private T GetNumericVal<T>(string sColName, T defVal = default(T)) where T : IConvertible
{
string sVal = GetStrVal(sColName);
try
{
return (T)Convert.ChangeType(sVal, typeof(T));
}
catch (FormatException)
{
return defVal;
}
}
Generic arguments, or arguments applied to an entire class or group of opposing arguments, occur frequently in academic debate. Many generic argument positions endure across debate resolutions.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
To make a generic type optional, you have to assign the void as the default value. In the example below, even though the function takes a generic type T, still you can call this function without passing the generic type and it takes void as default.
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it.
I haven't tried this but change T defVal = 0
to T defVal = default(T)
If you know that T will have a parameterless constructor you can use new T() as such:
private T GetNumericVal<T>(string sColName, T defVal = new T()) where T : new()
Otherwise you can use default(T)
private T GetNumericVal<T>(string sColName, T defVal = default(T))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With