tags:

views:

102

answers:

2

How should i implement, in C#, a class containing a property with the type of something and then that something example :

public class MyObject{
    public someEnum e { get; set;}
    public Object ObjectDependentOnE { get; set; }
}

I want to be able to return the right type for my object which depends on my enum. for example if e = 1, my object is of type T1...

or maybe I trying to do somethng wrong

any idea?

+4  A: 

I am unsure of what you are really trying to do, but it appears that generics is what you are looking for:

public class MyObject<T>
{
   public T SomeProperty{get;set;}
}

You can constraint T to classes that implement a given interface.

Usage would be:

MyObject<SomethingClass> something = new MyObject<SomethingClass>;
eglasius
That what not exactly what i had in mind but i guess it'll have to do
moi_meme
A: 

I'm not sure what your use case would be - more information might help answer this better, but from my guess, you may want to consider making a factory class instead. Something like:

class MyClass
{
    public SomeEnum E { get; set; }
    // This might be better as : public Object GetTheObject(SomeEnum E) and eliminating the above property
    public Object GetTheObject()
    {
         switch(this.E)
         {
         case E.Something:
            return new MySomethingObject(); // Or return an instance that already exists...?
         default:
            return new MyDefaultObject();
         }
    }
}

This could also be a property with a getter and setter, and get and set the specific object type.

However, I recommend considering rethinking the approach - this seems like a very error-prone design, since it has no type safety at compile time, and is very confusing from the consumer's POV.

Reed Copsey