type conversion in passed parameters

  • Thread starter Thread starter Mark Oliver
  • Start date Start date
M

Mark Oliver

Hi, I want to put a type conversion in my class, but I don't want the
conversion to be usable in a passed parameter because it makes no sense.

class cData
{
string s;

public cData(string s)
{
this.s=s;
}

public static implicit operator cData(string s)
{

cData data=new cData(null);
data.s=s;
return data;
}
public void f(cData data)
{
data.s=s;
}
} // class cData
void test()
{
string s="123";
cData data1=new cData("456");
data1=s; // this is OK, it's why I want the type conversion, data1
changes to a new cData with s="123"
// but I don't want this
data1.f(s); // C# passes reference types by reference - no type
converted parameters should be allowed
// it should be a compiler error - IT DOES NOTHING

cData data2=new cData("789");
data1.f(data2); // this is OK, it's why I want the function f, data2.s
changes to "456"
}
 
Mark,

I can see your problem. Since you implemented the implicit operator for
cData the string being passed to the f() method does a converstion.

Here is one idea, what if you changed the f() methods parameter to be of
type object. You could then, inside the method, make sure the type is of
type cData. If it's not you could always throw an exception.

Just a though.
 
I would suggest that you use an explicit cast, rather than an implicit
class. I know it's more work in places, but it fits the requirements of how
to use implicit and explicit casting styles.

Chris R.
 
Mark Oliver said:
Hi, I want to put a type conversion in my class, but I don't want the
conversion to be usable in a passed parameter because it makes no sense.

You can't - but personally I believe that implicit conversion operators
are a bad idea. However, I also notices this in your post:
data1.f(s); // C# passes reference types by reference - no type
converted parameters should be allowed

C# does *not* pass anything by reference unless you explicitly say so.
There is a difference between passing a reference by value and passing
a value by reference.

See http://www.pobox.com/~skeet/csharp/parameters.html
 
Hi, I took you idea, it sure beat looking through each of the 550 times I
used the type conversion in my code.
Thanks Very Much,
Mark
 
Back
Top