Nathalie De Crop
Nathalie De Crop

Reputation: 35

Generic class as return type

I have a storage class that uses generics to hold different values.

public class Setting<T>
{
    ...
}

In another class I want to make a method like

  public Setting<T> getSetting(string setting)
  {
        return (Setting<T>)settingDictionary[setting];
  }

Where settingDictionary is

 private Dictionary<string, object> settingDictionary;

I get error:

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

Is there a way to solve this? thanks

Upvotes: 2

Views: 1157

Answers (3)

Peter Hoogers
Peter Hoogers

Reputation: 1

Well the compiler does not know what "T" is, you can define it as a generic on the method like this:

public Setting<T> getSetting<T>(string setting)

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98830

Your Setting<T> class doesn't implement Dictionary<string, object> so you should make your method generic type like GetSetting<T>

public Setting<T> GetSetting<T>(string setting)
 {

 }

Here is a DEMO.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564671

You need to make the method generic:

 public Setting<T> GetSetting<T>(string setting)
 {
   // ... Your code...

Upvotes: 3

Related Questions