String Reference Type

L

Lars

Anthony Jones said:
Try it:-

public class Thing
{
private int x;
private Thing() {}
public Thing(x) { this.x = x}
public static Thing operator = (Thing RHS)
{
return new Thing(x);
}
}

Looks like it ought to work, doesn't compile though. = is not an
overloadable operator.

Can the following code really be compiled?
public Thing(x) { this.x = x} // What is x?

I think I got it.

Binary operators take two arguments and return a Boolean. Tried this on
strings and since Strings doesn't define the operators "<" ">" "<=" ">=" I
can't write those comparement operators unless I define how > and < should
work. A operator that takes one argument is unnary for example ++ --. Thats
why you can't wrote an assignment operator or + operator for that sake. you
can't define the operator as in the code below but you can't use it see the
code below again


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Lesson05
{
class Thing
{
private String X;

public void setX(String i) { X = i; }
public String getX() { return X; }

public Thing() {X="";}
public Thing( Thing anObject ) { setX(anObject.getX()); }

public static Boolean operator != (Thing T1, Thing T2) { return
T1.getX() != T2.getX(); }
public static Boolean operator == (Thing T1, Thing T2) { return
T1.getX() == T2.getX(); }

// This actually work
public static String operator + (Thing T1, Thing T2) { return
T1.getX()+ T2.getX(); }
}



public partial class functiontests : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
Thing a = new Thing();
Thing b = new Thing();
Thing c = new Thing();

// c = a+b; Does not work.

a.setX(TextBox1.Text);
b.setX(TextBox2.Text);


if (a == b) { Label1.Text += "<br>" + a.getX() + " == " +
b.getX() + "<br>"; }
if (a != b) { Label1.Text += "<br>" + a.getX() + " != " +
b.getX() + "<br>"; }


//if (a >= b) { Label1.Text += "<br>" + a.getX() + " >= " +
b.getX() + "<br>"; }
// Compiler error. String doesn't define operator >=
}
}
}


// Lars
 

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