Assigning different types of variables to the same type
As a very simplistic and silly example of what I mean, suppose I had the following class with a simple static property int
:
public class MyClass
{
public static int MyVar { get; set; }
}
So, if I wanted to set this property using code, it would be easy with something like:
MyClass.MyVar = 2;
But how could I take care (again to simplify the example) passing in string
and converting it to int
?
The only way I could think of would be to create a helper method like:
public class MyClass
{
public static int MyVar { get; private set; }
public static void SetMyVar(string sMyVar)
{
MyVar = int.Parse(sMyVar);
}
}
And then in running the code:
MyClass.SetMyVar("2");
I would like to know if there is a better way to do this than adding to this additional method.
source to share
While you definitely shouldn't be doing this because it's confusing to read, you can create a property this way
class MyClass
{
private static int _property = 0;
public static object Property
{
get
{
return _property;
}
set
{
_property = Convert.ToInt32(value);
}
}
}
You would need to pass this to an int whenever you wanted to use it as an integer, but this is the best I could think of.
source to share
is this what you were trying to do?
class newclass
{
private static int MyVarValue = 0;
public static int MyVar
{
get;
set
{
MyVarValue = Convert.ToInt32(value);
}
}
}
This will not compile because the value the property gets in must be of the same type as the property itself. But if you take a list of objects in the constructor and assign them to properties, you can do something like this ...
class newclass
{
private static int MyVarValue = 0;
public newclass(List<object> startingList)
{
MyVarValue = Convert.ToInt32(startingList[0]);
}
}
source to share
You can use compiler method overload resolution to select the SetMyValue method based on the type of the argument. Within each SetMyValue method, you have a mechanism to convert all of the different input values ββto the same base type.
This is probably a bad idea, but it doesn't matter here. It doesn't have enough semantics you are asking for, but it closes:
//A class with multiple 'set' methods that will silently handle
//type conversions
class MyClass{
private int myValue;
public int MyValue { { get return this.myValue; } }
public void SetMyValue(int value){
this.myValue = value;
}
public void SetMyValue(string value){
this.myValue = Convert.ToInt32(value);
}
}
In statically typed languages, switching silent ticks in such a way that they lose information is not a very wise idea. There are other dynamically typed languages ββthat allow you to play fast and fluently with types, but C # is not one of them. You have to get out of your way in C # to get dynamic typing.
This is probably a pain in the ass from a maintenance standpoint. I would put one more thought into the main problem you are trying to solve which will lead to this question.
source to share