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
  • 39,242
  • 6
  • 30
  • 78
Tono Nam
  • 34,064
  • 78
  • 298
  • 470

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
  • 187,200
  • 47
  • 362
  • 445
3

Implement the implicit operator.

MSDN implicit (C# Reference)

Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
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
  • 40,053
  • 20
  • 133
  • 188