Search code examples
c#typescastingredefine

C# redefine a variable in class


I'm sure about problem "types" in C #.

Suppose I have a class with the working name "item". This class has a field such as "variable". This field should match those of an element in my program, e.g. Boolean int16, int32, int64, double, uint, uint16.

Is there any possibility to redefine the type of a variable in dependency needs? Or is there any other approach to this problem?

I thought on the definition of this variable as var or object but then projecting it on a given type.

The problem is that the later the check when assigning values do not exceed the range?


Solution

  • You can either use generics, or dynamic, depending on how you want to use Item.

    To use the generics approach, define Item as such:

    class Item<T> {
        public T Variable { get; set; }
    }
    

    When you want an item whose Variable is an int, do this:

    var intItem = new Item<int>()
    // you can set the Variable property to an int now!
    intItem.Variable = -1;
    

    When you want an item whose Variable is a byte, do this:

    var byteItem = new Item<byte>()
    // you can set the Variable property to a byte
    byteItem.Variable = 10;
    

    And so on and so forth...

    One feature of this approach is that the item's Variable's type cannot be changed once the item is created. So this is not possible:

    intItem.Variable = "Hello";
    

    If you want to change its type to something else without creating a new item, you should use a dynamic variable:

    class Item {
        public dynamic Variable {get; set;}
    }
    

    You can now do something like this:

    var myItem = new Item();
    myItem.Variable = "Hello";
    myItem.Variable = 10;
    

    This is basically the same as defining Variable as object, but it saves your time casting between object and the desired type.

    And regarding your worry about checking whether the value is out of range, it might be a little hard to check it if you use dynamic. But I did this little test and found that when the value overflowed, it will just wrap around:

    var item = new Item();
    item.Variable = byte.MaxValue;
    item.Variable++;
    Console.WriteLine(item.Variable); // prints 0