473,728 Members | 1,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does x.ToString() throw an error if x == null?

If we have something like this

object x = null;
MessageBox.Show (x.ToString())

we get an error. That kindof makes sense but there is no reason the
behaviour couldn't be to return an empty string. When we call x.ToString we
are really calling a function like this:

class Object
{
public static string ToString(object * Instance)
{
//code to convert the object pointer to a string
}
}

Why can't the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:

string x = null;
MessageBox.Show (x.IsNullOrEmpt y.ToString())
MessageBox.Show (x.Length.ToStr ing()) //<--- shows zero
DateTime? y;
MessageBox.Show (y.IsValid)

The interesting thing is you can define extention methods that do work on
null objects, eg

static class Extensions
{
public static bool IsSomething(thi s string s)
{
return !string.IsNullO rEmpty(s);
}
public static string ToStringIgnoreN ull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}

Then use it like this:

string x = null;
if (x.IsSomething( )) MessageBox.Show (x)

or

object x = null;
MessageBox.Show (x.ToStringIgno reNull())

Any comments?

Cheers,
Michael

Aug 27 '08 #1
19 2716
"Michael C" <mi***@nospam.c omwrote in message
news:u7******** ******@TK2MSFTN GP03.phx.gbl...
[...] When we call x.ToString we are really calling a function like this:

class Object
{
public static string ToString(object * Instance)
{
No, not really. You can do that with extension methods (as you already
point out at the end of your message), but the real ToString is not static;
it is a virtual method that can be overridden in child classes:

class Object
{
public virtual string ToString()
{
return this.GetType(). Name;
}
}

This can't work if the object is null.

Aug 27 '08 #2
Even if you declare an object, it doesn't really exist yet until you have
initialized it and the compiler has not set aside any space for it.

To say, "Look at the space for this object that I have not created yet and
tell me what it says" would naturally throw an error.

What might be possible (though I wouldn't know how to do it) would be to
define behaviors for your compiler. If x is null, then the compiler or
language could return something useful (instead of crashing or running off
into oblivion). God knows that happens to me plenty!

"Michael C" wrote:
If we have something like this

object x = null;
MessageBox.Show (x.ToString())

we get an error. That kindof makes sense but there is no reason the
behaviour couldn't be to return an empty string. When we call x.ToString we
are really calling a function like this:

class Object
{
public static string ToString(object * Instance)
{
//code to convert the object pointer to a string
}
}

Why can't the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:

string x = null;
MessageBox.Show (x.IsNullOrEmpt y.ToString())
MessageBox.Show (x.Length.ToStr ing()) //<--- shows zero
DateTime? y;
MessageBox.Show (y.IsValid)

The interesting thing is you can define extention methods that do work on
null objects, eg

static class Extensions
{
public static bool IsSomething(thi s string s)
{
return !string.IsNullO rEmpty(s);
}
public static string ToStringIgnoreN ull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}

Then use it like this:

string x = null;
if (x.IsSomething( )) MessageBox.Show (x)

or

object x = null;
MessageBox.Show (x.ToStringIgno reNull())

Any comments?

Cheers,
Michael

Aug 27 '08 #3
"jp2msft" <jp*****@discus sions.microsoft .comwrote in message
news:8D******** *************** ***********@mic rosoft.com...
Even if you declare an object, it doesn't really exist yet until you have
initialized it and the compiler has not set aside any space for it.
The bulk of the object does exist even before you declare the object.
Generally the actual code will be greater than the object itself (in size)
and all of the code exists and is ready to call before an instance is
created.
To say, "Look at the space for this object that I have not created yet and
tell me what it says" would naturally throw an error.
There is no reason calling a function on a null object *has* to raise an
exception, the designers of C# just designed it that way. They actually
needed to put an extra check in to stop it working. Basically when you call,
say, object.ToString you end up calling a global function ToString where the
pointer to the object is passed in, ie

x.ToString();

translates to (under the hood of course)

public static string ToString(object * pObject)
{
//convert pObject to sring
}

I'm sure it's more complicated than that but that's the basic idea. The
compiler does the null check before the static function is called but there
is no reason that it needs to. It can easily call the static ToString
function and let that function decide whether to allow nulls or not.

Michael
Aug 28 '08 #4
"Alberto Poblacion" <ea************ *************** ***@poblacion.o rgwrote
in message news:e8******** ******@TK2MSFTN GP06.phx.gbl...
No, not really. You can do that with extension methods (as you already
point out at the end of your message), but the real ToString is not
static; it is a virtual method that can be overridden in child classes:
Technically the real ToString is not static, it's global. But as C# doesn't
have global functions I wrote it as static.
class Object
{
public virtual string ToString()
{
return this.GetType(). Name;
}
}

This can't work if the object is null.
Yes it can because the type tells you whether to call the original ToString
or the overridden ToString, eg

object x = null;
x.ToString(); //<-- calls the ToString defined by object

MyClass x = null;
x.ToString(); //<-- calls the ToString override on MyClass

being that the real to string function looks like this:

public static String ToString(MyClas s* Value)
{
}

Then it is possible to call on a null reference becase null can be passed in
to the Value parameter.

Michael
Aug 28 '08 #5
On Wed, 27 Aug 2008 19:27:45 -0700, Michael C <mi***@nospam.c omwrote:
"Alberto Poblacion" <ea************ *************** ***@poblacion.o rg>
wrote
in message news:e8******** ******@TK2MSFTN GP06.phx.gbl...
> No, not really. You can do that with extension methods (as you already
point out at the end of your message), but the real ToString is not
static; it is a virtual method that can be overridden in child classes:

Technically the real ToString is not static, it's global. But as C#
doesn't
have global functions I wrote it as static.
No, Object.ToString () is not static, and it's not global. It's a virtual
instance method in the Object class. Every type inherits Object and so
every object has the ToString() method. You are right that C# doesn't
have global functions, and that includes even Object.ToString ().
>class Object
{
public virtual string ToString()
{
return this.GetType(). Name;
}
}

This can't work if the object is null.

Yes it can because the type tells you whether to call the original
ToString
or the overridden ToString, eg
No, it can't. You cannot use any instance member of a class with a null
reference. In the case of ToString(), it's particularly problematic
because it's a virtual method and you need an instance to get at the
v-table. But even for non-virtual members the run-time requires an actual
instance.

In C++, for a non-virtual member, you could actually call the member with
a null reference. But even in C++ you can't call a virtual function with
a null reference. There's just no way that what you'd want to work could
work, because ToString() is virtual.
object x = null;
x.ToString(); //<-- calls the ToString defined by object
See above. It just can't work.
MyClass x = null;
x.ToString(); //<-- calls the ToString override on MyClass
See above. This _definitely_ can't work. Overrides are handled via a
v-table that is referenced from the object instance. No object instance,
no v-table, no way to call the method. There'd be no way for the run-time
to distinguish which version of the ToString() method should be called,
because static typing has nothing to do with choosing the implementation
for virtual methods.

For example, given that:

String x = "5";
Object obj = x;

obj.ToString();

winds up calling the String.ToString () implementation, what should happen
if you have:

String x = null;
Object obj = x;

obj.ToString();

To be consistent, it should call String.ToString (). But how is it to know
that should happen?
being that the real to string function looks like this:

public static String ToString(MyClas s* Value)
{
}
The real ToString() method doesn't look anything like that.

Pete
Aug 28 '08 #6
On Wed, 27 Aug 2008 19:20:11 -0700, Michael C <mi***@nospam.c omwrote:
[...]
There is no reason calling a function on a null object *has* to raise an
exception,
That's only partly true. For virtual methods, it _does_ have to raise an
exception.
the designers of C# just designed it that way.
I believe that this is a run-time rule. You can't call an instance method
on a null reference in C++/CLI either.
They actually
needed to put an extra check in to stop it working. Basically when you
call,
say, object.ToString you end up calling a global function ToString where
the
pointer to the object is passed in,
That's just not true.
[...]
I'm sure it's more complicated than that but that's the basic idea. The
compiler does the null check before the static function is called
There's no static function, and it's not the compiler generating the code
to do the check. It's part of the run-time.
but there
is no reason that it needs to. It can easily call the static ToString
function and let that function decide whether to allow nulls or not.
No, it can't.

Pete
Aug 28 '08 #7
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
No, Object.ToString () is not static, and it's not global.
I'm loathe to reply to you peter as I find you can be quite rude (and
usually very negative and unpleasant) but here goes for now.

Actually that is wrong, every function under the hood is global. It has a
location in memory and any code in the current process can call that
function. The C# IDE tricks us into thinking it's instance or static or
private or whatever.
It's a virtual instance method in the Object class. Every type inherits
Object and so every object has the ToString() method. You are right that
C# doesn't have global functions, and that includes even
Object.ToString ().
I'm talking about under the hood at the assembly level.
No, it can't. You cannot use any instance member of a class with a null
reference. In the case of ToString(), it's particularly problematic
because it's a virtual method and you need an instance to get at the
v-table. But even for non-virtual members the run-time requires an actual
instance.
There is no reason this can't be worked around.
For example, given that:

String x = "5";
Object obj = x;

obj.ToString();

winds up calling the String.ToString () implementation, what should happen
if you have:

String x = null;
Object obj = x;

obj.ToString();
Simple, it calls the Object.ToString .
To be consistent, it should call String.ToString (). But how is it to know
that should happen?
Obviously it should call Object.ToString .
>being that the real to string function looks like this:

public static String ToString(MyClas s* Value)
{
}

The real ToString() method doesn't look anything like that.
Really? What does it look like then peter?

Michael
Aug 28 '08 #8
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
That's only partly true. For virtual methods, it _does_ have to raise an
exception.
No, it can do whatever the designers decide it can do. They could have
called the ToString method if they had wanted to. Possibly there are
disadvantages but say it is not possible is just plain wrong.
That's just not true.
Oh yes it is (see, I can disagree with no detail too :-)
There's no static function,
Static was not the best choice of words but I've already explained why I
used that term. I'd repeat my explanation but it appears you've missed it a
couple of times already.
and it's not the compiler generating the code to do the check. It's part
of the run-time.
Big deal, there's still a compiler and the compiler could do whatever the
designers want.
No, it can't.
Oh yes it can stoopid.

>
Pete

Aug 28 '08 #9
On Wed, 27 Aug 2008 23:04:23 -0700, Michael C <mi***@nospam.c omwrote:
"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
>That's only partly true. For virtual methods, it _does_ have to raise
an
exception.

No, it can do whatever the designers decide it can do.
You should probably learn a little more about virtual methods (functions)
(particularly as they are implemented in langauges like C++, C#, VB.NET
and Java) before you make any more claims like that. Here's a decent
place to start:
http://en.wikipedia.org/wiki/Virtual_table
They could have
called the ToString method if they had wanted to. Possibly there are
disadvantages but say it is not possible is just plain wrong.
No, it's exactly right. By definition, a virtual method needs an
instance. The run-time can't just go picking arbitrary methods to call
when there's a null reference, and the compiler doesn't emit enough
information for the run-time to know what the static typing of the
variable was.
[...]
Oh yes it can stoopid.
Ah, right. I forgot that when you run out of words, you start calling
people names. That really helps you look credible.

Pete
Aug 28 '08 #10

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

Similar topics

7
1908
by: Fendi Baba | last post by:
The function is called from opencalendar(targetfield). Thanks for any hints on what could be the problem. .............................................................. var decimalPointDelimiter = ".";
2
2755
by: SammyBar | last post by:
Hi, I'm trying to bind a custom collection class to a data grid, following the guidelines from the article http://msdn.microsoft.com/msdnmag/issues/05/08/CollectionsandDataBinding/default.aspx. The problem is the article is in VisualBasic. I already get the collection to be recognized as a Data Source by the IDE. It populated the DataGrid correctly from the fields on the items object of the collection, but I can't get the DataGrid to...
13
5049
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
7
9999
by: Clint Herron | last post by:
Howdy! I posted this question on CSharpCorner.com, but then realized I should probably post it on a more active newsgroup. This will be my only cross-post. I'm creating a game engine, and using CodeDOM for my scripting needs (I realize I could use yacc or something else, but I wanted to try using CodeDOM -- this is more of an exercise for me to learn this stuff). Well, I compile my in-game scripts just fine. See appendix A for my code
7
2142
by: GS | last post by:
Hello, I'm receiving The state information is invalid for this page and might be corrupted error message when running code below. This happens on second post back. Why is it happening? My webpage contains 2 dropdowns controls and I save information entered by user in ViewState variable containing array ArrayList MyCoordinates = (ArrayList) ViewState ; if (MyCoordinates == null) { MyCoordinates = new ArrayList ();
2
9958
by: sree reddy | last post by:
..cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls;
1
4138
by: VAADADMIN | last post by:
I have a small app that I am working with to create LDIF files from text files. I have a pictureBox that has an animated GIF that will appear on the form when the LDIF are being created. The pictureBox appears and the GIF is there, but it does not stop when called. So when I debug, the RunWorkerCompleted event never fires. Is there anything in my code that is obvious as to why. private void createLDIF_btn_Click(object sender,...
0
2886
by: vishnu | last post by:
Hi, Am trying to post the data over https and am getting error in httpwebresponse.getResponseStream.Please help me to get rid of this issue. Here is the message from immediate window ?myResp.GetResponseStream() {System.Net.ConnectStream}
0
1751
by: dprjessie | last post by:
Hello, I am a Web programmer and I'm working on my first desktop application as a favor for a friend. I'm sure I have a stupid error here, but there is no error being thrown so I can't figure out what is wrong. I have code that reads an excel file and fills a datagridview and it works just fine. It is also supposed to fill a database though and that is not working. The executeNonQuery command is returning a 1 which as I understand, means it has...
0
8897
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
8756
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
9416
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
9126
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
8123
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
6012
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4524
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...
0
4787
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2159
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.