Reputation: 784
The title may not be so expecific, sorry for that. I'd like to know if there is a type of variable(or class or something) that works like the type "var" but outside a method, inside the class, I want to use it as a parameter like that:
public class ConfigParam
{
string paramName;
var paramValue;
public ConfigParam(string name, var value)
{
paramName = name;
paramValue = value;
}
public string ParamName
{
get { return paramName; }
set { paramName = value; }
}
public var ParamValue
{
get { return paramValue; }
set { paramValue = value; }
}
}
but the "var" type don't work outside method. Can anyone help me?
Upvotes: 1
Views: 500
Reputation: 1541
You can use object
public class ConfigParam
{
string paramName;
object paramValue;
public ConfigParam(string name, object value)
{
paramName = name;
paramValue = value;
}
public string ParamName
{
get { return paramName; }
set { paramName = value; }
}
public object ParamValue
{
get { return paramValue; }
set { paramValue = value; }
}
}
No type safety, but it will be working.
Upvotes: 1
Reputation: 106926
You need to use generics:
public class ConfigParam<T>
{
string paramName;
T paramValue;
public ConfigParam(string name, T value)
{
paramName = name;
paramValue = value;
}
public string ParamName
{
get { return paramName; }
set { paramName = value; }
}
public T ParamValue
{
get { return paramValue; }
set { paramValue = value; }
}
}
If you need to do more than store the type T
you can apply generic constraints.
Upvotes: 3