473,786 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what is this c# syntax?

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)sampleC onfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)
Nov 16 '05 #1
11 1721
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.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Davíð Þórisson" <db**@hi.is> wrote in message
news:OX******** ******@TK2MSFTN GP10.phx.gbl...
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)sampleC onfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)

Nov 16 '05 #2
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.

--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #3
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)sampleC onfig["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,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


"Davíð Þórisson" <db**@hi.is> wrote in message
news:OX******** ******@TK2MSFTN GP10.phx.gbl...
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)sampleC onfig["Title"];
2) class myParentPage = (default_aspx) this.Page;

(default_aspx is the class name for my parent Page)

Nov 16 '05 #4
Davíð Þórisson <db**@hi.is> wrote:
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)sampleC onfig["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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Davíð Þórisson <db**@hi.is> wrote:
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)sampleC onfig["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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
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?

"Morten Wennevik" <Mo************ @hotmail.com> wrote in message
news:opsghnvur2 klbvpo@pbn_comp uter...
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.

--
Happy Coding!
Morten Wennevik [C# MVP]

Nov 16 '05 #7
Davíð Þórisson <db**@hi.is> wrote:
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;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
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)sampleC onfig["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.It em("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

"Davíð Þórisson" <db**@hi.is> wrote in message
news:Ox******** *****@TK2MSFTNG P09.phx.gbl...
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?

Nov 16 '05 #9

"Bob Grommes" <bo*@bobgrommes .com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
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("goo dbye");
MyString b = (MyString)a;
}

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

/* *************** *** */
class YourString{
string val;
public YourString(stri ng t){val=t;}
public static implicit operator MyString (YourString t){
return new MyString("Hello ");
}
}
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
3307
by: David MacQuigg | last post by:
I'm concerned that with all the focus on obj$func binding, &closures, and other not-so-pretty details of Prothon, that we are missing what is really good - the simplification of classes. There are a number of aspects to this simplification, but for me the unification of methods and functions is the biggest benefit. All methods look like functions (which students already understand). Prototypes (classes) look like modules. This will...
37
2608
by: Bengt Richter | last post by:
ISTM that @limited_expression_producing_function @another def func(): pass is syntactic sugar for creating a hidden list of functions. (Using '|' in place of '@' doesn't change the picture much (except for people whose tools depend on '@' ;-)). I.e., (not having the source or time to delve) the apparent semantics of the above is something roughly like
70
8913
by: Roy Yao | last post by:
Does it mean "(sizeof(int))* (p)" or "sizeof( (int)(*p) )" ? According to my analysis, operator sizeof, (type) and * have the same precedence, and they combine from right to left. Then this expression should equal to "sizeof( (int)(*p) )", but the compiler does NOT think so. Why? Can anyone help me? Thanks. Best regards. Roy
121
10180
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather than a PHP IDE. It only supports basic IntelliSense (or code completion) and doesn't have anything...
8
4051
by: Hermawih | last post by:
Hello , I want your opinion about this . In order to say it clearly , I think I have to describe it in long sentences . I could consider myself as Intermediate/Advance Access Developer ; Intermediate/Advanced Database designer . Because of the requirements , I must create Web Application . Access Pages is not suitable for that so I think about learning VB Net / ASP Net . I am
6
407
by: Daniel Rudy | last post by:
What is wrong with this program? When I try to compile it, I get the following error. Compiler is gcc on FreeBSD. strata:/home/dcrudy/c 1055 $$$ ->cc -g -oe6-3 e6-3.c e6-3.c: In function `main': e6-3.c:32: syntax error before `||' e6-3.c:33: syntax error before `printf' e6-3.c:36: syntax error before `||' e6-3.c:40: syntax error before `(' e6-3.c:40: syntax error before `strcpy'
10
3237
by: Protoman | last post by:
Could you tell me what's wrong with this program, it doesn't compile: #include <iostream> #include <cstdlib> using namespace std; class Everything { public: static Everything* Instance()
3
16253
by: Manuel | last post by:
I'm trying to compile glut 3.7.6 (dowbloaded from official site)using devc++. So I've imported the glut32.dsp into devc++, included manually some headers, and start to compile. It return a very strange error. In your experience, where I should looking to find the real error? Surely the sintax of glut is correct... gcc.exe -c glut_bitmap.c -o glut_bitmap.o -I"C:/Dev-Cpp/include" -I"../../include" -D__GNUWIN32__ -W -DWIN32 -DNDEBUG...
5
2386
by: Cylix | last post by:
this.menus = { root: new Array };
14
9857
by: gimme_this_gimme_that | last post by:
What is going on here with the dollar signs and parenthesis? $(document).ready(function(){ $("li").behavior("click",function(){ $(this).load(menu.html"); }); }); And when do you use click vs. onclick? Is onclick only an attribute thing?
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9496
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.