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.

3
  • 5
    Kids , instead of downvoting , teach him. Commented Oct 30, 2012 at 14:50
  • Why would you want to do this? It looks confusing as hell. Commented Oct 30, 2012 at 14:50
  • @RoyiNamir: Prepare to be serial upvoted. Commented Oct 30, 2012 at 14:51

3 Answers 3

7

I think you want an implicit cast operator.

public static implicit operator MyClass(int m) 
{
     // code to convert from int to MyClass
}
Sign up to request clarification or add additional context in comments.

Comments

3

Implement the implicit operator.

MSDN implicit (C# Reference)

Comments

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.