Generics in .net 2.0

  • Thread starter Thread starter Søren Reinke
  • Start date Start date
S

Søren Reinke

Hi there

I have a problem, with key/value pairs in web.config.

The value is sometimes a boolean, sometimes an integer and sometimes a
string and so on.

Do i need to make a method for each type ?
Or can i use generics ?

I would like to be able to do something like:

Integer age=getConfigValue("KeyName",17); //name,default value if something
fails)
Boolean productionServer=getConfigValue("onProductionServer",false);

And more like that.
 
Personally, I would create an accessor for each type I expect to get out of
the .config file ...

GetInt()
GetDouble()
GetBoolean()

etc.

have a look at the post "Reccomended ways of saving WinForms' "viewstate"?"
in group "microsoft.public.dotnet.framework.windowsforms" for a sample
..config file reader/writer
 
billr said:
Personally, I would create an accessor for each type I expect to get out
of
the .config file ...

GetInt()
GetDouble()
GetBoolean()

That is what i have done, just interested in knowing if it was possible to
do in Generics.
 
Søren,

You should be able to use generics here, on the method level. You could
declare the method as:

// Name it GetConfigValue, not getConfigValue, since
// it is a violation of the public naming guidelines.
public T GetConfigValue<T>(string key, T defaultValue)
{
// Get the value here, it should be returned as an object.
object retVal = ...;

// Cast the return value.
return (T) retVal;
}

Hope this helps.
 
Be careful with that approach. If retVal is (for example) a boxed int, the
cast will throw an exception if T is anything other than int.

To really make this approach work, conversions are required.

I think this is not really a good application for generics.


Nicholas Paldino said:
Søren,

You should be able to use generics here, on the method level. You
could declare the method as:

// Name it GetConfigValue, not getConfigValue, since
// it is a violation of the public naming guidelines.
public T GetConfigValue<T>(string key, T defaultValue)
{
// Get the value here, it should be returned as an object.
object retVal = ...;

// Cast the return value.
return (T) retVal;
}

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Søren Reinke said:
That is what i have done, just interested in knowing if it was possible
to do in Generics.


--
Best regards C.T.O. Søren Reinke
www.Xray-Mag.com/ - Your free diving magazin on the net. Download it in
PDF
Aug-sept issue of X-RAY Magazine is ready to download:
EGYPT Finding Yolanda Wreck, Celebrate the Seas 2005
 
Ted Miller said:
Be careful with that approach. If retVal is (for example) a boxed int, the
cast will throw an exception if T is anything other than int.

To really make this approach work, conversions are required.

I think this is not really a good application for generics.

Okay, i'll just stick to 1 method per type :)
 
Back
Top