I have a class named config with two string fields named key paramValue and parameterPath.
When I apply the ChooseType method of the class, the method has to return one variable paramValue in different types (Int or bool or String).
I implemented it as follow:
class ConfigValue
{
public string parameterPath;
private string paramValue;
public ConfigValue(string ParameterPath="empty",string ParamValue="empty")
{
this.parameterPath = ParameterPath;
this.paramValue = ParameterPath;
}
public enum RetType { RetInt=1, RetBool, RetString };
public T ChooseType<T>(RetType how)
{
{
switch(how)
{
case RetType.RetInt:
return int.Parse(string this.paramValue);
break;
case RetType.RetBool:
return Boolean.Parse(string this.paramValue);
break;
case RetType.RetString:
return this.paramValue;
break;
}
}
}
}
But,I get error in switch operator in the next rows:
return int.Parse(string this.paramValue);
Error:
Only assignment, call, increment, decrement, and new object expressions can be used as a statement.
return Boolean.Parse(string this.paramValue);
Error:
Invalid expression term ‘string’.
return this.paramValue;
Error:
Cannot implicitly convert type ‘string’ to ‘T’.
Any idea why do I get these errors and how can I fix the code?
You should not specify parameter type when you are calling some method. Parameter types required only for method declaration. Thus just pass parameter:
Also you should add
defaultbranch for your switch block (you must return something if incorrect parameter value was passed to your method).Also you don’t need to
breakswitch branches if you already usedreturn.And for converting some type to generic value you should use
dynamic, or double conversion via object: