473,403 Members | 2,323 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

casting vs creating an instance

I'm doing my c# more and more like i used to code c++, meaning i'm casting
more often than creating an instance of objects.
like :
protected void gvOrderDetailsRowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
switch (((Sale)e.Row.DataItem).SzPN)
{
case "LTM0001":
case "ANU0001":
Person PER =
PersonManager.GetItem(((Sale)e.Row.DataItem).IPers onID);
if (PER.BActive)
((Label)e.Row.FindControl("lblOwner")).Text =
PER.FullName;
else
((Label)e.Row.FindControl("lblOwner")).Text = "Not
Yet Active";
break;
default:
break;
}
}
}

would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?
--
Share The Knowledge. I need all the help I can get and so do you!
Jun 27 '08 #1
19 1902
You seem to be inferring that a cast takes time at runtime.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Yankee Imperialist Dog" <Ya******************@discussions.microsoft.com>
wrote in message news:00**********************************@microsof t.com...
I'm doing my c# more and more like i used to code c++, meaning i'm casting
more often than creating an instance of objects.
like :
protected void gvOrderDetailsRowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
switch (((Sale)e.Row.DataItem).SzPN)
{
case "LTM0001":
case "ANU0001":
Person PER =
PersonManager.GetItem(((Sale)e.Row.DataItem).IPers onID);
if (PER.BActive)
((Label)e.Row.FindControl("lblOwner")).Text =
PER.FullName;
else
((Label)e.Row.FindControl("lblOwner")).Text = "Not
Yet Active";
break;
default:
break;
}
}
}

would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?
--
Share The Knowledge. I need all the help I can get and so do you!
Jun 27 '08 #2
that is possible. Does creating an instance take time at runtime where a cast
would not?
--
Share The Knowledge. I need all the help I can get and so do you!
"Bob Powell [MVP]" wrote:
You seem to be inferring that a cast takes time at runtime.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Yankee Imperialist Dog" <Ya******************@discussions.microsoft.com>
wrote in message news:00**********************************@microsof t.com...
I'm doing my c# more and more like i used to code c++, meaning i'm casting
more often than creating an instance of objects.
like :
protected void gvOrderDetailsRowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
switch (((Sale)e.Row.DataItem).SzPN)
{
case "LTM0001":
case "ANU0001":
Person PER =
PersonManager.GetItem(((Sale)e.Row.DataItem).IPers onID);
if (PER.BActive)
((Label)e.Row.FindControl("lblOwner")).Text =
PER.FullName;
else
((Label)e.Row.FindControl("lblOwner")).Text = "Not
Yet Active";
break;
default:
break;
}
}
}

would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?
--
Share The Knowledge. I need all the help I can get and so do you!
Jun 27 '08 #3
On Mon, 16 Jun 2008 15:51:06 -0700, Yankee Imperialist Dog
<Ya******************@discussions.microsoft.comwro te:
[...]
would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?
As Bob's reply suggests, casting really isn't a performance issue. It's
not true that it's completely free -- unless the compiler can tell that
the cast is perfectly safe (and most of the time, it can't), there's a
run-time check for the type. But the check is relatively insignificant.

That said, the real issue here is that you seem to be under the impression
that casting is equivalent to _creating_ an instance of an object. It's
not.

Now, it's possible that when you write "an instance created once", you
really just mean casting the value once as you assign it to a local
variable. And in fact, I would do that. Not because it's more
performant, but just because if you're using the value more than once, it
makes the code nicer to read.

But doing the cast doesn't create an instance, not even if you do it when
assigning to a local variable of the target type. If you're trying to
learn C#, it will be important for you to be careful about correctly
describing what the code is doing, and in particular describing a simple
assignment as "creating an instance" is incorrect and will likely lead to
misunderstandings in the future if that description continues to be used.

Pete
Jun 27 '08 #4
On Jun 17, 12:05 am, "Bob Powell [MVP]"
<bob@_spamkiller_bobpowell.netwrote:
You seem to be inferring that a cast takes time at runtime.
You seem to be implying that it doesn't ;)

Unless the compiler can guarantee that the cast is valid (and not even
then, sometimes) the cast *will* take time at execution time. Not a
lot, but some.

To the OP: I wouldn't worry about the performance side, but the
clarity side. Creating a new object and reuing an old one are usually
significantly different operations, wiith different implications. Go
with whatever produces the cleanest, most natural code. If you're
logically operating on an existing object, do so - if you're logically
creating a new one, do that instead :)

Jon
Jun 27 '08 #5
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in my
case is a class and as it is atomic in it's scope i guess this does make it a
variable. The root here is memory usage and time. From what all of you said
it seems that there really is no difference. Creating a variable of type
"Sale" and storing all the objects from the data row is not any different
than time or memory wise than casting for each object i need from that data
row.

Please correct me if i am wrong here

Thanks
--
Share The Knowledge. I need all the help I can get and so do you!
"Peter Duniho" wrote:
On Mon, 16 Jun 2008 15:51:06 -0700, Yankee Imperialist Dog
<Ya******************@discussions.microsoft.comwro te:
[...]
would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?

As Bob's reply suggests, casting really isn't a performance issue. It's
not true that it's completely free -- unless the compiler can tell that
the cast is perfectly safe (and most of the time, it can't), there's a
run-time check for the type. But the check is relatively insignificant.

That said, the real issue here is that you seem to be under the impression
that casting is equivalent to _creating_ an instance of an object. It's
not.

Now, it's possible that when you write "an instance created once", you
really just mean casting the value once as you assign it to a local
variable. And in fact, I would do that. Not because it's more
performant, but just because if you're using the value more than once, it
makes the code nicer to read.

But doing the cast doesn't create an instance, not even if you do it when
assigning to a local variable of the target type. If you're trying to
learn C#, it will be important for you to be careful about correctly
describing what the code is doing, and in particular describing a simple
assignment as "creating an instance" is incorrect and will likely lead to
misunderstandings in the future if that description continues to be used.

Pete
Jun 27 '08 #6
On Jun 17, 1:26 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwro te:
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in my
case is a class and as it is atomic in it's scope i guess this does make it a
variable. The root here is memory usage and time. From what all of you said
it seems that there really is no difference. Creating a variable of type
"Sale" and storing all the objects from the data row is not any different
than time or memory wise than casting for each object i need from that data
row.

Please correct me if i am wrong here
It feels like your terminology is still a bit off - a class can't be
atomic, for example.

Could you post a short but *complete* program demonstrating what you
mean?

Certainly creating instances and casting *are* different in time and
memory, but whether or not they're *significantly* different will
depend on the situation.

Jon
Jun 27 '08 #7
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;
if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The question
here is, as implied from other answers/comments above. Is SAL a "Variable" of
Type Sale or an "Instance" of type Sale. I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that it's
values can vary, but i've always considered an object created from a class to
be an instance(?)

That asside say i'm going to be setting the 50 public properties of object SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
....
....
.... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the latter.

Thanks
--
Share The Knowledge. I need all the help I can get and so do you!
"Jon Skeet [C# MVP]" wrote:
On Jun 17, 1:26 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwro te:
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in my
case is a class and as it is atomic in it's scope i guess this does make it a
variable. The root here is memory usage and time. From what all of you said
it seems that there really is no difference. Creating a variable of type
"Sale" and storing all the objects from the data row is not any different
than time or memory wise than casting for each object i need from that data
row.

Please correct me if i am wrong here

It feels like your terminology is still a bit off - a class can't be
atomic, for example.

Could you post a short but *complete* program demonstrating what you
mean?

Certainly creating instances and casting *are* different in time and
memory, but whether or not they're *significantly* different will
depend on the situation.

Jon
Jun 27 '08 #8
And your code is so ugly it is OOOGLY ;-)
Here's some resources to help you make the suggested transition...

http://msdn.microsoft.com/en-us/library/czefa0ke.aspx
http://dotnet.mvps.org/dotnet/faqs/?...ingconventions

<%= Clinton Gallagher
"Yankee Imperialist Dog" <Ya******************@discussions.microsoft.com>
wrote in message news:9A**********************************@microsof t.com...
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;
if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The
question
here is, as implied from other answers/comments above. Is SAL a "Variable"
of
Type Sale or an "Instance" of type Sale. I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that
it's
values can vary, but i've always considered an object created from a class
to
be an instance(?)

That asside say i'm going to be setting the 50 public properties of object
SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the
latter.

Thanks
--
Share The Knowledge. I need all the help I can get and so do you!
"Jon Skeet [C# MVP]" wrote:
>On Jun 17, 1:26 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwr ote:
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in
my
case is a class and as it is atomic in it's scope i guess this does
make it a
variable. The root here is memory usage and time. From what all of you
said
it seems that there really is no difference. Creating a variable of
type
"Sale" and storing all the objects from the data row is not any
different
than time or memory wise than casting for each object i need from that
data
row.

Please correct me if i am wrong here

It feels like your terminology is still a bit off - a class can't be
atomic, for example.

Could you post a short but *complete* program demonstrating what you
mean?

Certainly creating instances and casting *are* different in time and
memory, but whether or not they're *significantly* different will
depend on the situation.

Jon
Jun 27 '08 #9
And your code is so ugly it is OOGLY ;-)
Here's some resources to help you make the suggested transition...

http://msdn.microsoft.com/en-us/library/czefa0ke.aspx
http://dotnet.mvps.org/dotnet/faqs/?...ingconventions

<%= Clinton Gallagher
"Yankee Imperialist Dog" <Ya******************@discussions.microsoft.com>
wrote in message news:9A**********************************@microsof t.com...
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;
if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The
question
here is, as implied from other answers/comments above. Is SAL a "Variable"
of
Type Sale or an "Instance" of type Sale. I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that
it's
values can vary, but i've always considered an object created from a class
to
be an instance(?)

That asside say i'm going to be setting the 50 public properties of object
SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the
latter.

Thanks
--
Share The Knowledge. I need all the help I can get and so do you!
"Jon Skeet [C# MVP]" wrote:
>On Jun 17, 1:26 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwr ote:
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in
my
case is a class and as it is atomic in it's scope i guess this does
make it a
variable. The root here is memory usage and time. From what all of you
said
it seems that there really is no difference. Creating a variable of
type
"Sale" and storing all the objects from the data row is not any
different
than time or memory wise than casting for each object i need from that
data
row.

Please correct me if i am wrong here

It feels like your terminology is still a bit off - a class can't be
atomic, for example.

Could you post a short but *complete* program demonstrating what you
mean?

Certainly creating instances and casting *are* different in time and
memory, but whether or not they're *significantly* different will
depend on the situation.

Jon
Jun 27 '08 #10
On Jun 17, 2:36 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwro te:
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
What makes you think that's creating an object? It's not. It's not
creating anything, it's just casting a reference.
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;

if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The question
here is, as implied from other answers/comments above. Is SAL a "Variable" of
Type Sale or an "Instance" of type Sale.
SAL itself is definitely a variable.
I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that it's
values can vary, but i've always considered an object created from a class to
be an instance(?)
It's neither an object, nor an instance. It's a variable. It's a local
variable which has a particular value.

Here's another example:

int x = 0;

"x" isn't an int. It's a variable of type int. The *value* of x is an
int.
That asside say i'm going to be setting the 50 public properties of object SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the latter.
Well it doesn't make sense to perform a cast 60 times or indeed
evaluate the Row and DataItem properties 60 times, and personally I
don't like the readability of the version which casts all the time, so
I'd use the former. What do you like about the latter?

Jon
Jun 27 '08 #11
On Tue, 17 Jun 2008 06:36:00 -0700, Yankee Imperialist Dog
<Ya******************@discussions.microsoft.comwro te:
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
That's not an example of "create an object".

Perhaps I wasn't emphatic enough before: it is ABSOLUTELY CRITICAL that
you use the correct terminology. Even in daily communication, using words
in their normal, expected way is important. But in a technical field like
programming, we have very specific concepts and very specific words and
phrases to describe those concepts. As a community we've already agreed
upon the usage, and if you start using words and phrases to mean something
than what they already mean, it's very difficult to understand what you
mean.

At best, we have to guess from the context what you're really talking
about and at worst, we can collectively waste a whole lot of time
answering a completely different question from what you've asked.
[...]
ok I think we can agree that SAL it is an object of Type Sale. The
question
here is, as implied from other answers/comments above. Is SAL a
"Variable" of
Type Sale or an "Instance" of type Sale.
Sorry to be the bearer of bad news, but that's only a question in your
mind. :)
I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that
it's
values can vary, but i've always considered an object created from a
class to
be an instance(?)
You didn't _create_ the object with the cast. You cast an existing
reference to an existing object from one type to another. The only thing
that changed was how your code views the object. The actual object didn't
change, and no new object was created.

And yes, "SAL" is a variable. It is not the object itself, but rather a
reference to the object. When you cast a different reference to the type
"Sale", you assigned the exact same value that was in "e.Row.DataItem" to
the variable "SAL". The cast doesn't change the value, it just tells the
compiler "yes, I really meant to do this". Then at run-time, the .NET
Framework run-time checks the types for each variable (the source
"e.Row.DataItem" and the destination "SAL") and verifies that what's
contained in the source is in fact compatible with the destination (i.e.
makes sure that it's actually a instance of "Sale").

This run-time check takes a little time, and that's why we've said there's
some overhead. But the time spent is _really_ small. It's not of any
concern in most code, and even in code where performance is critical,
avoiding multiple casts is highly unlikely to be an optimization that
would be of any use.
That asside say i'm going to be setting the 50 public properties of
object SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
Well, you could in fact test it yourself. But no, I do not believe you
would be able to find any measurable, significant difference between the
two, even though there's a theoretical performance difference.
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the
latter.
Well, if you like the latter, use it. Personally, I find the latter
harder to read and more verbose. As I mentioned before, I'd prefer the
former. But if you really really like the latter, there's no real
performance reason to avoid it.

Pete
Jun 27 '08 #12
lol Point taken my friend. In truth i'd more than likely use Reflection where
i could and live with the performance hit where 60 needed. I guess i was
just trying to get an answer as to if there was a difference in terms of
performance. Consider it an accademic issue.

As was pointed out by Peter, I tend to get sloppy on terms, but i really do
try to make the code fun as well as readable.
--
Share The Knowledge. I need all the help I can get and so do you!
"Jon Skeet [C# MVP]" wrote:
On Jun 17, 2:36 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwro te:
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;

What makes you think that's creating an object? It's not. It's not
creating anything, it's just casting a reference.
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;

if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The question
here is, as implied from other answers/comments above. Is SAL a "Variable" of
Type Sale or an "Instance" of type Sale.

SAL itself is definitely a variable.
I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that it's
values can vary, but i've always considered an object created from a class to
be an instance(?)

It's neither an object, nor an instance. It's a variable. It's a local
variable which has a particular value.

Here's another example:

int x = 0;

"x" isn't an int. It's a variable of type int. The *value* of x is an
int.
That asside say i'm going to be setting the 50 public properties of object SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the latter.

Well it doesn't make sense to perform a cast 60 times or indeed
evaluate the Row and DataItem properties 60 times, and personally I
don't like the readability of the version which casts all the time, so
I'd use the former. What do you like about the latter?

Jon
Jun 27 '08 #13
Thank you for responding. Deep down i understood all that and i did use the
wrong words. You point was taken.

--
Share The Knowledge. I need all the help I can get and so do you!
"Peter Duniho" wrote:
On Tue, 17 Jun 2008 06:36:00 -0700, Yankee Imperialist Dog
<Ya******************@discussions.microsoft.comwro te:
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;

That's not an example of "create an object".

Perhaps I wasn't emphatic enough before: it is ABSOLUTELY CRITICAL that
you use the correct terminology. Even in daily communication, using words
in their normal, expected way is important. But in a technical field like
programming, we have very specific concepts and very specific words and
phrases to describe those concepts. As a community we've already agreed
upon the usage, and if you start using words and phrases to mean something
than what they already mean, it's very difficult to understand what you
mean.

At best, we have to guess from the context what you're really talking
about and at worst, we can collectively waste a whole lot of time
answering a completely different question from what you've asked.
[...]
ok I think we can agree that SAL it is an object of Type Sale. The
question
here is, as implied from other answers/comments above. Is SAL a
"Variable" of
Type Sale or an "Instance" of type Sale.

Sorry to be the bearer of bad news, but that's only a question in your
mind. :)
I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that
it's
values can vary, but i've always considered an object created from a
class to
be an instance(?)

You didn't _create_ the object with the cast. You cast an existing
reference to an existing object from one type to another. The only thing
that changed was how your code views the object. The actual object didn't
change, and no new object was created.

And yes, "SAL" is a variable. It is not the object itself, but rather a
reference to the object. When you cast a different reference to the type
"Sale", you assigned the exact same value that was in "e.Row.DataItem" to
the variable "SAL". The cast doesn't change the value, it just tells the
compiler "yes, I really meant to do this". Then at run-time, the .NET
Framework run-time checks the types for each variable (the source
"e.Row.DataItem" and the destination "SAL") and verifies that what's
contained in the source is in fact compatible with the destination (i.e.
makes sure that it's actually a instance of "Sale").

This run-time check takes a little time, and that's why we've said there's
some overhead. But the time spent is _really_ small. It's not of any
concern in most code, and even in code where performance is critical,
avoiding multiple casts is highly unlikely to be an optimization that
would be of any use.
That asside say i'm going to be setting the 50 public properties of
object SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";

Well, you could in fact test it yourself. But no, I do not believe you
would be able to find any measurable, significant difference between the
two, even though there's a theoretical performance difference.
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the
latter.

Well, if you like the latter, use it. Personally, I find the latter
harder to read and more verbose. As I mentioned before, I'd prefer the
former. But if you really really like the latter, there's no real
performance reason to avoid it.

Pete
Jun 27 '08 #14
I appreciate the references. Yes the code is as you say. Some times it's fun
to do something just to be different life's to short. Just being curious
about performance. Pretty don't always mean smart. However, as i noted below
i'd use reflection if i had to set 50 or more if i could.

Programmer time is often more costly than computer time needed to execute,
but not always. Just got to know when to do what.

--

"clintonG" wrote:
And your code is so ugly it is OOOGLY ;-)
Here's some resources to help you make the suggested transition...

http://msdn.microsoft.com/en-us/library/czefa0ke.aspx
http://dotnet.mvps.org/dotnet/faqs/?...ingconventions

<%= Clinton Gallagher
"Yankee Imperialist Dog" <Ya******************@discussions.microsoft.com>
wrote in message news:9A**********************************@microsof t.com...
i'll describe

Sale is a class. Having firstname, lastname, .......
if i create an object ("by casting the DataItem to type of Sale)
Sale SAL = ((Sale)e.row.DataItem;
if (SAL.SzPn == "YYY")
SAL.FirstName;
SAL.LastName;
if i cast the DataItem to
if (((Sale)e.Row.DataItem).SzPN == "YYY")
(((Sale)e.Row.DataItem).SzFirstName;
(((Sale)e.Row.DataItem).SzLastName;
....;
ok I think we can agree that SAL it is an object of Type Sale. The
question
here is, as implied from other answers/comments above. Is SAL a "Variable"
of
Type Sale or an "Instance" of type Sale. I, up to this point, would have
considered it an instance. However, it suggested above by another poster
(Peter) that it should be considered a variable(?) Now i understand that
it's
values can vary, but i've always considered an object created from a class
to
be an instance(?)

That asside say i'm going to be setting the 50 public properties of object
SAL
is there a time or memory difference between
Sale SAL = ((Sale)e.row.DataItem;
SAL.FirstName = "TTT";
....
....
... to property #50
and
(((Sale)e.Row.DataItem).SzFirstName = "TTT";
...
...
... to row 50

It may be splitting hairs, but I'm curious, because i tend to like the
latter.

Thanks
--
Share The Knowledge. I need all the help I can get and so do you!
"Jon Skeet [C# MVP]" wrote:
On Jun 17, 1:26 pm, Yankee Imperialist Dog
<YankeeImperialist...@discussions.microsoft.comwro te:
Thank You for replying, all of you.
Perhaps my terms were off and i stand corrected. The local variable in
my
case is a class and as it is atomic in it's scope i guess this does
make it a
variable. The root here is memory usage and time. From what all of you
said
it seems that there really is no difference. Creating a variable of
type
"Sale" and storing all the objects from the data row is not any
different
than time or memory wise than casting for each object i need from that
data
row.

Please correct me if i am wrong here

It feels like your terminology is still a bit off - a class can't be
atomic, for example.

Could you post a short but *complete* program demonstrating what you
mean?

Certainly creating instances and casting *are* different in time and
memory, but whether or not they're *significantly* different will
depend on the situation.

Jon

Jun 27 '08 #15
To every one: This has been a fun discussion i really think this is how
knowledge gets shared. I take no offence to any comments and i do not intend
to offend.

Thanks. I tearned something from each of you!!
--
Share The Knowledge. I need all the help I can get and so do you!
"Yankee Imperialist Dog" wrote:
I'm doing my c# more and more like i used to code c++, meaning i'm casting
more often than creating an instance of objects.
like :
protected void gvOrderDetailsRowDataBound(object sender,
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
switch (((Sale)e.Row.DataItem).SzPN)
{
case "LTM0001":
case "ANU0001":
Person PER =
PersonManager.GetItem(((Sale)e.Row.DataItem).IPers onID);
if (PER.BActive)
((Label)e.Row.FindControl("lblOwner")).Text =
PER.FullName;
else
((Label)e.Row.FindControl("lblOwner")).Text = "Not
Yet Active";
break;
default:
break;
}
}
}

would an instance created once for (Sale)e.Row.DataItem,
where the row is bound to a custom business object, be faster, slow or no
different than just casting the e.row.DataItem each time i need a value?
--
Share The Knowledge. I need all the help I can get and so do you!
Jun 27 '08 #16
I think that the times type checking is employed at runtime are pretty
infrequent, especially for common cases.

I tried the following;

#1 a class cast to an interface
#2 direct call to the classes implementation
#3 direct call to a class method not used as an interface implementation
#4 call to a derived class cast to a base
#5 direct call to a derived class method
#6 cast from variable of type object to specific type

in all cases the compiler worked out the correct info and the IL was pretty
much the same except for the type of the final object.

To clarify;

#1 object was type a
#2 object was type a
#3 object was type a
#4 object was type aderived
#5 object was of type aderived
#6 object was of type a

The stopwatch times to make 10000 calls to methods that themselves made a
thousand iterations, non optimised, were virtually identical.

While I understand that the circumstance arises occasionally, as a
performance issue, I think the question of casting is a non-starter.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:10**********************************@j22g2000 hsf.googlegroups.com...
On Jun 17, 12:05 am, "Bob Powell [MVP]"
<bob@_spamkiller_bobpowell.netwrote:
>You seem to be inferring that a cast takes time at runtime.

You seem to be implying that it doesn't ;)

Unless the compiler can guarantee that the cast is valid (and not even
then, sometimes) the cast *will* take time at execution time. Not a
lot, but some.

To the OP: I wouldn't worry about the performance side, but the
clarity side. Creating a new object and reuing an old one are usually
significantly different operations, wiith different implications. Go
with whatever produces the cleanest, most natural code. If you're
logically operating on an existing object, do so - if you're logically
creating a new one, do that instead :)

Jon
Jun 27 '08 #17
On Jun 19, 3:03*pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:
Change which line in the loop is commented out to see the difference
between casting and not. I've explicitly made sure that the
GetSampleObject() method is always called so that the only difference
in the loop should be the cast.

Analysis ought to show that the return value is unused and optimize away the
cast. *The function itself can't be optimized away because you've specified
NoInlining, of course, and I guess that prevents the JIT from inspecting it
for side effects and removing it, but there's no such barrier to eliminating
storage of the return value, is there?
True, true. I did at one point use the value, but removed it to keep
things simpler.

Would you expect a simple nullity test to be enough to prohibit that?

(Of course the return value *is* used when there's a cast, because the
cast might fail.)

Jon
Jun 27 '08 #18
Jon Skeet [C# MVP] wrote:
On Jun 19, 3:03 pm, "Ben Voigt [C++ MVP]" <r...@nospam.nospamwrote:
>>Change which line in the loop is commented out to see the difference
between casting and not. I've explicitly made sure that the
GetSampleObject() method is always called so that the only
difference in the loop should be the cast.

Analysis ought to show that the return value is unused and optimize
away the cast. The function itself can't be optimized away because
you've specified NoInlining, of course, and I guess that prevents
the JIT from inspecting it for side effects and removing it, but
there's no such barrier to eliminating storage of the return value,
is there?

True, true. I did at one point use the value, but removed it to keep
things simpler.

Would you expect a simple nullity test to be enough to prohibit that?

(Of course the return value *is* used when there's a cast, because the
cast might fail.)
Good point. I guess whether you think the compiler needs to preserve that
depends on whether you see the InvalidCastException as error recovery or
general-purpose flow control. So ultimately it is a side-effect which is
part of the public contract and the compiler can't remove it.
>
Jon

Jun 27 '08 #19
Ben Voigt [C++ MVP] <rb*@nospam.nospamwrote:
True, true. I did at one point use the value, but removed it to keep
things simpler.

Would you expect a simple nullity test to be enough to prohibit that?

(Of course the return value *is* used when there's a cast, because the
cast might fail.)

Good point. I guess whether you think the compiler needs to preserve that
depends on whether you see the InvalidCastException as error recovery or
general-purpose flow control. So ultimately it is a side-effect which is
part of the public contract and the compiler can't remove it.
Yes, I think it's sufficiently well-defined that it can't be removed.

However, the storage *could* be removed for the non-casting version,
which is what I thought you were originally referring to :)

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #20

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

Similar topics

7
by: Andrea Williams | last post by:
I have two objects and one inherits the other and adds a few more properties. Say I populate the first object with the properties, then want to cast it to be the second object, then I would be...
0
by: Michel | last post by:
Hi all! I created a new class, which has the UserControl as a base class. Now I want to create an instance of my new class, by creating a new usercontrol and casting it to my new class using...
7
by: S. Lorétan | last post by:
Hi guys, Sorry for this stupid question, but I don't know why it isn't working. Here is my (example) code: namespace Test { class A { public string Label1; }
8
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is...
14
by: Daniel | last post by:
Hi guys who just answered me.....it really would have helped if i had written it right. Ok i will use better names to explain my problem. I have this: InterFaceClass ^ ClassA
11
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? ...
3
by: per9000 | last post by:
Hi, can I reach a hidden method when doing ugly inheritance in python? .... def spin(self, n): print "A", n .... .... def spin(self, m): print "B", m .... .... def spin(self, k):...
4
by: casul | last post by:
Hi All, Given the following code that just defines a dummy class "my_class" and a dummy wrapper "my_wrapper" with a main program : #include <iostream> template< typename _Tag > class...
2
by: shapper | last post by:
Hello, I have created a class that inherits MembershipUser: public class UserHelper : MembershipUser { .... Then I am creating a user as follows: UserHelper user =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.