Logo 
Search:

C# FAQ

Submit Interview FAQ
Home » Interview FAQ » C#RSS Feeds

Are C# references the same as C++ references?

  Shared By: Jarrod Williams    Date: Sep 01    Category: C#    Views: 690

Answer:

Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.

For example, look at the following method:

void displayStringLength( string s )
{
Console.WriteLine( "String is length {0}", s.Length );
}
The problem with this method is that it will throw a NullReferenceException if called like this:

string s = null;
displayStringLength( s );
Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:

void displayStringLength( string s )
{
if( s == null )
Console.WriteLine( "String is null" );
else
Console.WriteLine( "String is length {0}", s.Length );
}

Share: 
 

Didn't find what you were looking for? Find more on Are C# references the same as C++ references? Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: