tags:

views:

100

answers:

3

How do i change the following statement so it accepts any type instead of long? Now here is the catch, if there is no constructor i dont want it compiling. So if theres a constructor for string, long and double but no bool how do i have this one line work for all of these support types?

ATM i just copied pasted it but i wouldnt like doing that if i had 20types (as trivial as the task may be)

public static explicit operator MyClass(long v) { return new MyClass(v); }
A: 

Use Object type, if I'm not mistaken.

public static explicit operator MyClass(object v) { return new MyClass(v); }
this. __curious_geek
nope. take a guess why
acidzombie24
may be the constructor thing is the constraint you need. Can you please more details in your kind as to how you want to use it in client-code.. ?
this. __curious_geek
I think its not possible. But the problem is object is a type so the compiler will look for a MyClass(object) constructor.
acidzombie24
+2  A: 

Maybe it works:

public static explicit operator MyClass<T>(T t) where T:new()
{ 
  return new MyClass(t);
}

EDIT

I checked your request just now and found sth weird. "So if theres a constructor for string, long and double but no bool" Can you tell me why you want to do this.

EDIT

I tried on my machine, it seems that generic types can't be used in explicit methods. Maybe we can only go back to an object parameter?

Danny Chen
nope. it thinks MyClass is a generic<T>. error --> The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
acidzombie24
Bonus: The non-generic type 'MyClass' cannot be used with type arguments
acidzombie24
What do you mean it thinks MyClass is a generic<T>? AFAIK this is the correct implementation of your request.
GrayWizardx
If you read the error msg i pasted above the C# compiler think that the return type is MyClass<T> as in `class MyClass<T> { ...`
acidzombie24
+1  A: 

Now I can tell you that the answer to you question is "No, we can't" because:

User-defined conversion must convert to or from the enclosing type.

That's why we can't use generic types here.

public class Order
{
    public string Vender { get; set; }
    public decimal Amount { get; set; }
}

public class AnotherOrder
{
    public string Vender { get; set; }
    public decimal Amount { get; set; }
    public static explicit operator AnotherOrder(Order o)
    {
        //this method can be put in Order or AnotherOrder only
    }
}
Danny Chen