what is this c# syntax?

D

Davíð Þórisson

hi
I'm new to c# and although having read 2 tutorials I cannot find what the
parenthesis in these 2 example situations mean;

1) string strKeyValue = (string)sampleConfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)
 
N

Nicholas Paldino [.NET/C# MVP]

Davíð,

In this case, "(string)" and "(default_aspx)" are casts. They allow you
to perform conversions (in the case of primitive value types), or convert a
reference of one type to another (assuming that the conversion is valid).

Hope this helps.
 
M

Morten Wennevik

Hi Davið,

(string) is a cast. It is used for type conversion (between class names,
structs, interfaces etc). It indicates that sampleConfig["Title"] returns
something other than a string, typically an object. To be able to use
this object as a string you first need to cast it back to a string, by
using (string).

Consider object o = 1;
int i = o;

Now, even though o contains a number, it cannot be directly stored as an
int. You need to tell the compiler you are aware of the dangers by
putting (int) in front of o.

int i = (int)o;

Casting changes the "appearance" of the object and you need to cast to the
correct class to be able to perform specific tasks on the objects.

Consider an ArrayList. It can hold any number of objects, and all
different kinds of objects at the same time.
However, internally, the ArrayList considers all these objects to be of
type Object, the basic type all other types in .Net Framework inherits
from. When you retrieve an object from an ArrayList it returns the Object
"signature" so no matter what type it was when you put it in, you cannot
do anything with it other than the stuff belonging to Object, like
ToString() and GetType(). You need to cast the object back to the
original type (class, struct, interface, etc).

ArrayList a = new ArrayList();
string s = "hello world";
a.Add(s);

string s = (string)a[0]; // a[0] returns an Object

Don't confuse the class type Object with the "physical" object (the thing,
which can be any class, struct, value, array, enum, interface ...).

I'm not sure if this helps you in any way, and some further code samples
might be in order, but perhaps others can fill in.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

It is a cast expression, to convert one expression to a given type. You have
to be careful though that the expression being cast can be converted to the
target type, this may not enforced by the compiler and you can get a runtime
exception. this is used a lot currently for example in collections,
ArrayList is a collection of objects instances, that you may have to cast to
the correct type to be able to use it.

now , regarding the examples that you use:

1) string strKeyValue = (string)sampleConfig["Title"];

I prefer to write:
string strKeyValue = sampleConfig["Title"].ToString();
please note that the above will never give you error !!!. and you may end
with the incorrect value ( usually the fully qualified name of the class ).


2) class myParentPage = (default_aspx) this.Page;

This should give you compilation error, the correct syntax is:
object myParentPage = (default_aspx) this.Page;

or
default_aspx myParentPage = (default_aspx) this.Page;


Cheers,
 
J

Jon Skeet [C# MVP]

Davíð Þórisson said:
I'm new to c# and although having read 2 tutorials I cannot find what the
parenthesis in these 2 example situations mean;

1) string strKeyValue = (string)sampleConfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)

They're both casts. I strongly suggest that you ditch ASP.NET for a
while, start learning C# and .NET with simple console applications, and
then move onto ASP.NET only after you know the basics.
 
D

Davíð Þórisson

thx everyone, I'm familiar to casts just didn't know this was the syntax
Jon I've already been reading for 2 weeks now I want to experiment

Davíð Þórisson said:
I'm new to c# and although having read 2 tutorials I cannot find what the
parenthesis in these 2 example situations mean;

1) string strKeyValue = (string)sampleConfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)

They're both casts. I strongly suggest that you ditch ASP.NET for a
while, start learning C# and .NET with simple console applications, and
then move onto ASP.NET only after you know the basics.
 
D

Davíð Þórisson

one last thought Morten, when casting say array to string, what or who
defines how to convert the data, is it a built in method of the array object
or is some other "standard" method used?
 
J

Jon Skeet [C# MVP]

Davíð Þórisson said:
one last thought Morten, when casting say array to string, what or who
defines how to convert the data, is it a built in method of the array object
or is some other "standard" method used?

You can't convert an array to a string using a cast.

Using a cast does one of three things:

1) Performs no actual conversion, just changes the type of reference to
something else which the actual object is compatible with. For
instance:

object o = "hello";
string s = (string)o;

2) Performs an implicit or explicit type-defined conversion. For
instance:

SqlInt32 x = new SqlInt32(10);
int i = (int)x;

3) Performs an unboxing operation - here the type must be *exactly*
that of the boxed value:

object o = 10;
int i = (int)o;
 
B

Bob Grommes

Simple value types have conversion rules that are defined by the C# language
specification.

To successfully cast any reference type A to B, A and B must have an
inheritance relationship with one another.

Since everything inherits from "object", it can be used as a container of
sorts for any other type. Once you put any type t into an instance of type
object, o, you can always retreive it by casting o to t -- that is, "t
myInstance = (t)o". When this is done with value types it's called boxing
and unboxing -- a special behavior implemented by the abstract class,
ValueType, from which all value types (structures and enums) derive.

You mention casting an array to a string. Your original example was:

string strKeyValue = (string)sampleConfig["Title"];

You can't cast an array to a string because one is not an ancestor of the
other. sampleConfig["Title"] is a member of the sampleConfig collection,
which is a collection of objects. The (string) cast gets you the string
that was stored in the instance of type object called sampleConfig["Title"].

Technically, what you are casting from is sampleConfig.Item("Title").
sampleConfig["Title"] is an "indexer", a bit of C# syntax sugar that lets
you define and use an array-like syntax to access members of collections.

--Bob
 
R

Roy Fine

Bob Grommes said:
Simple value types have conversion rules that are defined by the C# language
specification.

To successfully cast any reference type A to B, A and B must have an
inheritance relationship with one another.

not exactly true - what about the implicit conversion operator.

Consider the following in which there is absolutely no inheritance
relationship between MyString and YourString - yet the cast works as defined
:

regards
roy fine


/* ****************** */
public void Test(){
YourString a = new YourString("goodbye");
MyString b = (MyString)a;
}

/* ****************** */
class MyString{
string val;
public MyString(string t){val=t;}
}

/* ****************** */
class YourString{
string val;
public YourString(string t){val=t;}
public static implicit operator MyString (YourString t){
return new MyString("Hello");
}
}
 
B

Bob Grommes

Roy,

Well then perhaps I should rephrase it this way:

"To successfully cast any reference type A to B, A and B must either have an
inheritance relationship with one another, or A must have an appropriate
user-defined type conversion operator defined for type B."

Thanks for the nice refinement.

--Bob
 
R

Roy Fine

bob, well done.

rlf

Bob Grommes said:
Roy,

Well then perhaps I should rephrase it this way:

"To successfully cast any reference type A to B, A and B must either have an
inheritance relationship with one another, or A must have an appropriate
user-defined type conversion operator defined for type B."

Thanks for the nice refinement.

--Bob
 

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