Syntax error: Overloading the = operator?

G

Guest

Hello,

Thanks for reviewing my question. I am trying to override the = operator
for my UserControl class; However, I am getting a syntax error.

public class MyClass
{
private int x = 0;

public static UserControl1 operator =(int y)
{
x= y;
return this;
}
}

My goal is to offer an assignment similar to this:

MyClass B;
b = 1;

Many Thanks
Peter
 
G

Guest

I am trying to override the = operator

This is not allowed in C#. However, you can provide an implicit type
conversion operator instead that will do what you want:

public class MyClass
{
private int x = 0;

public MyClass(int y)
{
x = y;
}

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

This should work now:

MyClass B;
b = 1;

Mark
 
N

Nicholas Paldino [.NET/C# MVP]

Peter,

You can not override the = operator in C#. You will have to find
another way. You might want to look into overloading an implicit cast
operator. Check out the documentation on the implicit keyword for more
information.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top