Maxime Michel
Maxime Michel

Reputation: 615

Cast generic class to different type

NOTE : I am going to simplify the structure and contents of the class, it is much more complex in reality but the rest of it isn't necessary to the issue at hand.

I have the following (simplified) class structure :

public abstract class Config
{
    // A number of abstract parameters and special abstract methods
}

public class GenericConfig<T> : Config
{
    private DataType configDataType;
    public DataType ConfigDataType
    {
        get { /* A get function */ }
        set { /* A set function */ }
    }
    public T InitialValue { get; set; }
    public T MinValue { get; set; }
    public T MaxValue { get; set; }
    // Overridden parameters and methods
}

public enum DataType
{
    Int,
    Bool,
    Float,
    String,
    DateTime
}

When I instantiate a Config object, it looks like this :

Config configInstance = new GenericConfig<int>(..., ConfigDataType=0, ...)

What I would like to be able to do is cast the int type to float or anything from a method call. Something like the following (I'd preferably like to follow my enum types):

configInstance.CastType("Float") OR configInstance.CastType(2) which would give me the equivalent of :

Config configInstance = new GenericConfig<float>(..., ConfigDataType=2, ...)

Is this even remotely possible or is it something that should be avoided ?

Upvotes: 2

Views: 85

Answers (1)

user12031933
user12031933

Reputation:

I think you may consider to rethink or improve your design (why ConfigDataType is nedeed) but you can use operator explicit casting like this:

static public explicit operator GenericConfig<int>(GenericConfig<T> value)
{
  if ( typeof(T) is int ) return (GenericConfig<int>)value;
  return null;
}

static public explicit operator GenericConfig<float>(GenericConfig<T> value)
{
  if ( typeof(T) is float ) return (GenericConfig<float>)value;
  return null;
}

Create a new instance and process the conversion by copy instead of returning null.

Usage:

Config v1 = new GenericConfig<int>();
Config v2 = (GenericConfig<float>)v1;

Upvotes: 1

Related Questions