what does this mean ?

  • Thread starter Thread starter Maersa
  • Start date Start date
M

Maersa

hi all,

what does the following mean ?

class A
{
public string @return;
}

also, once an object is casted to class "A" how do i recast it to a "string"
?

object o = invoke(.......);
A a = (A)o;
string s = (string)a; /// doesn't work .

thanks,
 
Maersa said:
what does the following mean ?

class A
{
public string @return;
}

That's showing that it's got a member variable called "return" - the @
is to distinguish it from the return keyword. It's a really bad idea to
use keywords as variable names though.
also, once an object is casted to class "A" how do i recast it to a "string"
?

You can't cast objects just anywhere - they have to either have an
explicit or implicit conversion, or the object has to be an instance of
the class you're casting to.
object o = invoke(.......);
A a = (A)o;
string s = (string)a; /// doesn't work .

No, it wouldn't. What do you want to get out of it though? There are
any number of strings which *could* represent that instance of A. You
could override ToString in A, and call that, or write a new method
which returns an appropriate string, depending on what you want to do,
exactly.
 
hi all,

what does the following mean ?

class A
{
public string @return;
}

It means that the A has a public string called @return. My guess is the @ is added because 'return' is a keyword and can't be used as variable name.
also, once an object is casted to class "A" how do i recast it to a "string"
?

object o = invoke(.......);
A a = (A)o;

For this to work, o must be some version of A in disguise
string s = (string)a; /// doesn't work .

No because a isn't a string. You can however add a method to class A

public override string ToString()
{
return "Hello World!";
}

Which will work when A is used for string building.

A a = new A();
MessageBox.Show("" + a);

object o = "Hello World!";
string s = (string)o; // this works, because o is actually a string

object o = new A();
A a = (A)o; // this works, because as above o is actually A.

You can test if a cast will work with

if(o is string);
{
string s = (string)o;
}
else if(o is A)
{
A a = (A)o;
}
 
I should probably add the all this has to do with inheritance and casting. All objects know what they were originally created to be, even though they appear to be something else later on. The objects can be casted to itself or anything it inherits from, as well as interfaces it implements.

All objects (as far as I know) is ultimately derived from the object class, so you can cast everything to object (make it pretend to be of the object class) but you have to obey strict casting rules to cast the object to something else.

Happy coding!
Morten Wennevik [C# MVP]
 
Back
Top