3

Possible Duplicate:
Overloading assignment operator in C#

I remember I saw this question somewhere in stack overflow but I cannot find it.

Basically I will like to be able to do:

MyClass myClass = 5;

where MyClass is a class implemented by my program.

I will delete this question if I can find that duplicate.

Waldi
  • 31,868
  • 6
  • 18
  • 66
Tono Nam
  • 31,694
  • 75
  • 272
  • 444

3 Answers3

7

I think you want an implicit cast operator.

public static implicit operator MyClass(int m) 
{
     // code to convert from int to MyClass
}
Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
3

Implement the implicit operator.

MSDN implicit (C# Reference)

Austin Salonen
  • 47,582
  • 15
  • 104
  • 136
1

try this:

public class MyClass
{
    public int MyProperty { get; set; }

    private MyClass(int i)
    {
        MyProperty = i;
    }

    public static implicit operator MyClass(int x)
    {
        return new MyClass(x);
    }
}

MyClass myClass = 5;
TheVillageIdiot
  • 38,965
  • 20
  • 129
  • 186