Syntax error: Overloading the = operator?

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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
 
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.
 
Back
Top